This is the sixth day of my participation in the August Text Challenge.More challenges in August

1, Object. Keys method

The object. keys method is a JavaScript method used to iterate over Object properties. It takes an object as an argument and returns an array containing all the property names of the object. Such as:

var cat= {
	name:'mini'.age:2.color:'yellow'.desc:'cute'
}
console.log(Object.keys(cat)); // ["name", "age", "color", "desc"]
Copy the code

Keys: an array of keys greater than 2 in an Object

var data = {a: 1.b: 2.c: 3.d: 4};
Object.keys(data).filter(function(x) { return 1; }) Expected output: [" c ", "d"]Copy the code

What do you fill in here 1?

1: Data [x]>2

Keys is a new method in ES5 that fetches all the enumerable property names of the Object itself, but not the properties in the stereotype, and returns an array of property names. Note that it is the same as for.. In does not guarantee that the attributes will be printed in the original order of the objects.

Object. GetOwnPropertyNames and a new method of es5, all its attributes of the objects of returning the property name (including an enumerated attribute) consisting of an array, but you don’t get on the prototype chain properties.

  • Array.filter(function) Returns arrays that meet the criteria.

2, object.values () method

The Object.values method returns an array of all the key values of an Enumerable property of the parameter Object itself (not including inheritance).

var obj = { foo: "bar".baz: 42 };  
Object.values(obj)  
// ["bar", 42]  
Copy the code

Returns the order of the members of the array. The property named value is traversed by the size of the value, so the order returned is B, C, and A. Object.values returns only traversable properties of the Object itself.

var obj = { 100: 'a'.2: 'b'.7: 'c' };  
Object.values(obj)  
// ["b", "c", "a"]  
Copy the code

If the Object. Values method takes a string, it returns an array of characters.

Object.values(‘foo’) // [‘f’, ‘o’, ‘o’] In the above code, the string is first converted to an array-like Object. Each character of the string is an attribute of the object. Therefore, Object.values returns the key value of each attribute, which is an array of characters. If the parameter is not an Object, object. values will be converted to an Object first. Since numeric and Boilerwrapped objects, no non-inherited attributes are added to the instance. So, Object.values returns an empty array.

3, the Object. The create ()

The object.create () method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object. grammar

  • Object.create(proto, [propertiesObject])

The proto argument is the prototype object of the newly created object. PropertiesObject optional. If it is not specified as undefined, it is the property descriptor and corresponding property name of the object to be added to the newly created object for enumerable properties (that is, properties defined by itself, rather than enumerated properties in its stereotype chain). These properties correspond to the second argument to Object.defineProperties(). Returns a new object with the specified prototype object and properties. Such as:

var parent = { x : 1, y : 1 } var child = Object.create(parent,{ z : {// z becomes the property of the new object, writable:true, 64x :true, value: "newAdd"}}); console.log(child)//{z: "newAdd"}z: "newAdd"__proto__: x: 1y: 1__proto__: Function A(){this.a = 1; this.b = 2; } A.prototype.drive = function(){ console.log('drivvvvvvvvvv'); Function B(){} b.protoType = object.create (new A()); Function C(){a.call (this); } C.prototype = Object.create(A.prototype) //Copy the code

What’s the difference between these two approaches?

  • Disadvantages of 1:

Executing new is equivalent to running A again, and there are side effects if you do something else in A (such as changing global variables). Use the object created by A as A prototype, which may have some redundant properties.

  • 2 simulates the execution process of new

Object.hasownproperty (

Checks whether the object has the specified attribute in its own attributes.

obj.hasOwnProperty(‘name’)

HasOwnProperty (‘×××’). This method does not include methods on the object prototype chain

var obj = {
    name:'fei'
}
    console.log(obj.hasOwnProperty('name'))//true
    console.log(obj.hasOwnProperty('toString'))//false
Copy the code

This method returns true if the name attribute of an obj object exists. We know that the toString method exists on the prototype chain of each object instance. False indicates that this method only indicates the properties of the object instance, not the properties of the prototype chain.

5, Object. GetOwnPropertyNames () method

Object. GetOwnPropertyNames () method returns the Object all its attributes of the attribute name (including an enumerated attribute) consisting of an array, but you don’t get on the prototype chain properties.

function A(a,aa) {
  this.a = a;
  this.aa = aa;
  this.getA = function() {
    return this.a; }}// Prototype method
A.prototype.aaa = function () {};

var B = new A('b'.'bb');
B.myMethodA = function() {};
// Non-enumerable methods
Object.defineProperty(B, 'myMethodB', {
  enumerable: false.value: function() {}});Object.getOwnPropertyNames(B); // ["a", "aa", "getA", "myMethodA", "myMethodB"]
ObjectGetOwnPropertyNames andObject. Keysq differenceObjectGetOwnPropertyNames andObjectThe difference between keys, i.eObject.keys only applies to enumerable attributes, whileObject.getownPropertyNames Returns all the automatic property names of the object.
'use strict';
(function(){
    if(!Object.getOwnPropertyNames){
        console.log('Browser does not support getOwnPropertyNames');
        return;
    }

    // The human constructor
    var person = function(name, age, sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.sing = function(){
            console.log('sing'); }}/ / new a ladygaga
    var gaga = new person('ladygaga'.26.'girl');

    // Give Gaga an unenumerable ID card
    Object.defineProperty(gaga, 'id', {
        value : '1234567890'.enumerable : false
    });

    // Check Gaga's profile
    var arr = Object.getOwnPropertyNames(gaga);
    document.write(arr); //output: name,age,sex,sing,id

    document.write('</br>');// Note that unlike getOwnPropertyNames, non-enumerable ids are not output
    var arr1 = Object.keys(gaga);
    document.write(arr1); //output: name,age,sex,sing}) ();Copy the code

6, es6 javascript Object method object.assign ()

The object. assign method is used to merge objects. It copies all the enumerable attributes of the source Object to a shallow copy of the target Object.

var target = { a: 1 };
var source1 = { b: 2 };
var source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
Copy the code

1. If the target object has an attribute with the same name as the source object, or multiple source objects have an attribute with the same name, the later attribute overrides the previous one.

2. If there is only one parameter, object. assign returns that parameter.

var obj = {a: 1};  
Object.assign(obj) === obj // true  
Copy the code

3. If the parameter is not an object, it is converted to an object and then returned.

4. Undefined and NULL cannot be converted to objects, so an error is reported if they are used as arguments.

5, Object.assign implements shallow copy, not deep copy. That is, if the value of an attribute of the source object is an object, the target object copies a reference to that object.

var obj1 = {a: {b: 1}};  
var obj2 = Object.assign({}, obj1);  
obj1.a.b = 2;  
obj2.a.b / / 2In the code above, the value of the a property of the source object obj1 is an object,ObjectThe.assign copy yields a reference to this object. Any changes to this object are reflected on the target object.Copy the code

Common Uses (1) Add attributes to objects

class Point {  
    constructor(x, y) {  
        Object.assign(this, {x, y}); }}Copy the code

The above method adds the x and y attributes to the Object instance of the Point class using object. assign.

(2) Add methods for objects

Object.assign(SomeClass.prototype, {  
    someMethod(arg1, arg2){...}.anotherMethod(){...}});// This is the same as the following
SomeClass.prototype.someMethod = function (arg1, arg2) {...}. SomeClass.prototype.anotherMethod =function () {...}.Copy the code

The above code uses a concise representation of object properties, placing the two functions in curly braces and adding the assign method to someclass.prototype. (3) Clone objects

function clone(origin) {  
    return Object.assign({}, origin);  
} 
Copy the code

The code above copies the original object into an empty object, and you get a clone of the original object. However, in this way, cloning can only clone the value of the original object itself, not its inherited value. (4) Merge multiple objects Merge multiple objects into one object.

const merge =(target, ... sources) = > Object.assign(target, ... sources); If you want to return a new object after the merge, you can rewrite the above function to merge an empty object.const merge =(. sources) = > Object.assign({}, ... sources);Copy the code

(5) Specify default values for attributes

const DEFAULTS = {  
    logLevel: 0.outputFormat: 'html'  
};  
function processContent(options) {  
    let options = Object.assign({}, DEFAULTS, options);  
} 
Copy the code

In the above code, the DEFAULTS object is the default value and the Options object is the user-supplied parameter. The object. assign method merges DEFAULTS and options into a new Object. If they have the same property, the value of the option property overrides the value of the DEFAULTS property. Note that due to deep-copy problems, all properties of DEFAULTS and Options objects can only be of simple types and cannot point to another object. Otherwise, this property of the DEFAULTS object will not work.

7. Understand object.defineProperty () method

Object.defineproperty can be used to define new attributes or modify existing ones

Use constructors to define objects and properties

var obj = new Object; //obj = {}
obj.name = "Zhang"; // Add a description
obj.say = function(){}; // Add behaviorgrammarObject.defineProperty(obj, prop, Descriptor) Parameter Description OBj: Mandatory. Target object prop: Required. Attribute name descriptor to be defined or modified: required. Properties owned by target properties Add property descriptions to properties of objects, currently available in two forms: data description and accessor descriptionCopy the code

When you modify or define a property of an object, add some properties to the property. The properties in the data description are optional

var obj = {
test:"hello"
}
Object.defineproperty (obj,"test",{object.defineProperty (obj,"test",{
configurable:true | false.enumerable:true | false.value: A value of any type,writable:true | false
});
Object.defineproperty (obj,"newKey",{object.defineProperty (obj,"newKey",{
configurable:true | false.enumerable:true | false.value: A value of any type,writable:true | false}); Value: Sets the value of an attributewritable: Indicates whether the value can be rewritten.true | false
enumerable: Indicates whether the target attribute can be enumerated.true | false
configurable: Whether the target attribute can be deleted or whether the attribute can be modified againtrue | falseAccessor description When using accessor description properties, the following properties are allowed. When using getter or setter methods, the writable and Value properties are not allowedvar obj = {};
Object.defineProperty(obj,"newKey", {get:function (){} | undefined.set:function (value){} | undefined
configurable: true | false
enumerable: true | false}); Getter /setter a getter is a way of getting the value of a property and a setter is a way of setting the value of a property. Use the GET /set attribute to define the corresponding methodvar obj = {};
var initValue = 'hello';
Object.defineProperty(obj,"newKey", {get:function (){
// The function that fires when a value is fetched
return initValue;
},
set:function (value){
// The function that is triggered when a value is setinitValue = value; }});// Get the value console.log(obj.newKey); //hello

/ / set the value
obj.newKey = 'change value';

console.log( obj.newKey ); //change value
Copy the code