Common methods of Object in JavaScript

Common methods of Object

Object.getPrototypeOf()

Object. The getprototypeof method returns the prototype of the parameter object. This is the standard way to get prototype objects.

var F = function () {};
var f = new F();
Object.getPrototypeOf(f) === F.prototype // true

Prototypes of several special objects

// The prototype of an empty object is object prototype
Object.getPrototypeOf({}) === Object.prototype // true

// Object. The prototype of prototype is null
Object.getPrototypeOf(Object.prototype) === null // true

// The prototype of the function is function prototype
function f() {}
Object.getPrototypeOf(f) === Function.prototype // true

Object.setPrototypeOf()

Object. The setprototypeof method sets the prototype for the parameter object and returns the parameter object. It accepts two parameters, the first is an existing object and the second is a prototype object.

var a = {};
var b = {x: 1};
Object.setPrototypeOf(a, b);

Object.getPrototypeOf(a) === b // true
a.x // 1

Object. The setprototypeof method sets the prototype of object a to object b, so a can share the properties of b.

Object.create()

This method takes an object as a parameter, and then takes it as the prototype to return an instance object. The instance fully inherits the properties of the prototype object.

// Prototype object
var A = {
  print: function () {
    console.log('hello');
  }
};

// Instance object
var B = Object.create(A);

Object.getPrototypeOf(B) === A // true
B.print() // hello
B.print === A.print // true

Object. The create () method takes the a object as the prototype and generates the B object. B inherits all the properties and methods of A.

  Object.create = function (obj) {
    function F() {}
    F.prototype = obj;
    return new F();
  };

The above code shows that object The essence of the create () method is to create an empty constructor F, then make the F.prototype attribute point to the parameter object obj, and finally return an instance of F, so as to make the instance inherit the attributes of obj.

Object. The create () method can also accept the second parameter. This parameter is a property description object. The object properties described by it will be added to the instance object as the properties of the object itself.

var obj = Object.create({}, {
  p1: {
    value: 123,
    enumerable: true,
    configurable: true,
    writable: true,
  },
  p2: {
    value: 'abc',
    enumerable: true,
    configurable: true,
    writable: true,
  }
});

// Equivalent to
var obj = Object.create({});
obj.p1 = 123;
obj.p2 = 'abc';

Object.prototype.isPrototypeOf()

The isPrototypeOf method of the instance object is used to judge whether the object is the prototype of the parameter object.

var o1 = {};
var o2 = Object.create(o1);
var o3 = Object.create(o2);

o2.isPrototypeOf(o3) // true
o1.isPrototypeOf(o3) // true

Both o 1 and O 2 are prototypes of O 3. This indicates that the isPrototypeOf method returns true as long as the instance object is on the prototype chain of the parameter object.

Object.prototype.isPrototypeOf({}) // true
Object.prototype.isPrototypeOf([]) // true
Object.prototype.isPrototypeOf(/xyz/) // true
Object.prototype.isPrototypeOf(Object.create(null)) // false

In the above code, due to object Prototype is at the top of the prototype chain, so it returns true for all instances, except for objects directly inherited from null.

Object.assign()

For cloning

Only the enumerable properties of the source object itself will be copied to the target object, which is a shallow copy. If the attribute in the target object has the same key, the attribute will be overwritten by the attribute in the source object.

var first = {name : 'kong'};
var last = {age : 18};
var person = Object.assign(first, last);
console.log(person);//{name : 'kong', age : 18}

Object.is()

Used to judge whether the two values are the same

Object.is(a, b); //Return true or false
//Note that unlike the = = operator, this function does not cast any type,
//It should be more like = = =, but it's worth noting that it treats + 0 and - 0 as different
Object.is(+0, -0)  // false
Object.is(NaN, NaN)  // true
Object.is(NaN, 0/0)  // true
+0 === -0 // true
NaN === NaN // false

Object.keys()

Returns the names of the enumerable properties and methods of the object

var a = {name : 'kong', age : 18, func : function(){}};
Object.keys(a); //['name', 'age', 'func']

Object.entries()

Returns an array of key value pairs of enumerable attributes of a given object. The keyword is itself, and its arrangement is consistent with the order returned when traversing the object using the [for...in] loop (the difference is that the for in loop also enumerates the attributes in the prototype chain).

let obj1 = {
    a: 'aaa',
    b: 'bbb'
}

console.log(Object.entries(obj1)); // [ [ 'a', 'aaa' ], [ 'b', 'bbb' ] ]

// So you can easily convert the object into a map
let map = new Map(Object.entries(obj1))
console.log(map); // Map(2) { 'a' => 'aaa', 'b' => 'bbb' }

Object.freeze()

Freeze an object. The frozen object cannot be modified.

  1. Cannot add new attribute
  2. You cannot delete an existing attribute
  3. Enumerability, configurability and Writeability of existing attributes of an object cannot be modified
  4. Existing attribute values cannot be modified (shallow objects cannot be modified, only one layer, and objects after the second time can still be modified)
  5. Frozen object prototypes cannot be modified

If the above operations are performed in strict mode, an error will be reported, and the non strict mode will be ignored.

let obj1 = {
    a: 'aaa',
    b: 'bbb',
    c: {
        d: 'cccc'
    }
}

let obj2 = Object.freeze(obj1)

console.log(obj1 === obj2); // true returns the original object

// But the modification is invalid

obj2.a = 'hhh'
console.log(obj2); // { a: 'aaa', b: 'bbb', c: { d: 'cccc' } }

obj2.c.d = 'cheny'
console.log(obj2); // {A: 'AAA', B: 'BBB', C: {D: 'CHENY'}} despite one layer, deep objects can still be modified

Object.getOwnPropertyNames(obj)

Returns an array of property names of all its own properties of the specified object (including non enumerable properties but excluding those with Symbol values as names)

var obj = { 0: "a", 1: "b", 2: "c"};
console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"]

Object.prototype.hasOwnProperty()

The hasOwnProperty() method is used to determine whether an object contains a specified self property

obj.hasOwnProperty("Attribute name");//Whether the instance obj contains attributes in parentheses. If yes, it returns true; otherwise, it returns false

All inherit object Prototype objects will inherit from the prototype chain to the hasOwnProperty method, which detects whether an object contains a specific property,
Unlike in, this method ignores attributes inherited from the prototype chain.

This method cannot check whether the property exists in the prototype chain of the object. The property must be a member of the object itself.

var o =new Object();
o.prop="exists";

function change(){
  o.newprop=o.prop;
  delete o.prop;
}

o.hasOwnProperty("prop")//true
change()//Delete prop attribute of o
o.hasOwnProperty("prop")//false
//After deletion, use hasOwnProperty() to judge whether it exists. The returned value is no longer present

propertyIsEnumerable()

Determines whether the specified attribute is enumerable. (only consider their own attributes, not those on the prototype chain)

let obj1 = {
    a: 'aaa',
    b: 'bbb'
}

let obj2 = {
    c: 'ccc',
    d: 'ddd',
    __proto__: obj1
}
Object.defineProperty(obj2, 'e', {
    enumerable: false,
    value: 'eee'
})

console.log(obj2.e); // eee

console.log(obj2.propertyIsEnumerable('c')); // Own enumerable property true
console.log(obj2.propertyIsEnumerable('a')); // Inherited enumerable properties are not considered. So false is returned
console.log(obj2.propertyIsEnumerable('e')); // Own enumerable property false

Object.getOwnPropertyDescriptor()

Returns the property descriptor of the object's own property.

let obj = {}
Object.defineProperty(obj, 'name', {
    configurable: true,
    value: 'cheny',
    writable: true,
    enumerable: true
})

console.log(obj.name); // cheny
let desc = Object.getOwnPropertyDescriptor(obj, 'name')
console.log(typeof desc); // object
console.log(desc);
/*
{
  value: 'cheny',
  writable: true,
  enumerable: true,
  configurable: true
}
*/

Object.getOwnPropertyDescriptors()

The descriptor used to get all the attributes of an object.

let obj = {}
Object.defineProperties(obj, {
    'name': {
        value: 'John',
        writable: true,
    },
    'age': {
        value: '18',
        writable: false,
    }
})

console.log(obj.name);// John
console.log(obj.age);// 18

let desc = Object.getOwnPropertyDescriptors(obj)
console.log(desc);
/*
{
  name: {
    value: 'John',
    writable: true,
    enumerable: false,
    configurable: false
  },
  age: {
    value: '18',
    writable: false,
    enumerable: false,
    configurable: false
  }
}
*/

Object.seal()

Enclose an object, prevent the addition of new properties, and mark all existing properties as non configurable. The value of the current property can be changed as long as it is writable.

Usually, an object is Scalable (you can add new attributes). Sealing an object will make it impossible to add new properties, and all existing properties will become unconfigurable. The effect of non configurable attribute is that the attribute cannot be deleted, and a data attribute cannot be redefined as an accessor attribute, or vice versa. However, the value of the property can still be modified. An attempt to delete a property of a sealed object or convert a property of a sealed object from a data property to an accessor property will silently fail or throw an exception TypeError (in) Strict mode The most common but not the only).

Properties inherited from the prototype chain are not affected. but __proto__ The value of () attribute cannot be modified.

Returns a reference to the sealed object.

let obj1 = {
    a: 'aaa',
    b: 'bbb'
}

// Make objects closed
let obj2 = Object.seal(obj1)
console.log(obj1 === obj2); // true

// All properties of an object that becomes closed are not configurable, so strict mode will report an error when trying to delete a property
delete obj1.a
console.log(obj1); // {a: 'aaa', b: 'bbb'} was not deleted successfully

Traverse the object to get key or value

1.Object. Get key s () on all objects

2.Object.values() gets all value s on the object

3.Object.entries() gets the key and value on the object and returns a two-dimensional array, such as: [[a, 'aaa'], [b, 'bbb']]

4.Object.fromEntries(), converting the list of key value pairs into objects

Note that the above methods can only obtain their own enumerable key s or value s, which cannot be obtained on the prototype chain. This is the difference between them and for in. Using for in will also obtain the enumerable attributes on the prototype chain.

However, including the above methods and for in, only enumerable attributes can be obtained, while non enumerable, and Symbol attributes cannot be obtained

Get all key s, including enumerations, and symbol s

  1. Object.getOwnPropertyNames() gets the key s of all its properties, including non enumerable properties. It only contains string properties, not Symbol properties
  2. Object.getOwnPropertySymbols() gets the key s of all its Symbol properties. If the object has no Symbol property, it will return an empty array

for in

for...in statement traverses the enumerable properties of an object other than Symbol in any order, including inherited enumerable properties.

const obj = {
  name: "nordon",
  age: 12
};

for (const key in obj) {
  console.log(key, '---', obj[key]);
}

//console output 
name --- nordon
age --- 12

Keywords: Javascript Front-end data structure

Added by chiaki*misu on Sun, 06 Mar 2022 12:50:19 +0200