Object. Create (NULL) is used to define a mapping dictionary, instead of defining an Object literal. What is the difference between the two
let m = Object.create(null);
let n = {};
// What is the difference between m and n
console.log(m);
console.log(n);
Copy the code
Is a purely empty object
An empty object that inherits the object stereotype, i.e., n.tostring ();
Object. The create (proto, [propertiesObject]) method
- Proto The prototype object of the new object
- PropertiesObject Optional, property added to the new Object (not a property of the stereotype chain), enumerable by default, and corresponding to the second argument of Object.defineProperties
{} is equivalent to object.create (Object.ptototype), now you see the difference
for… In traverses enumerable properties of n (same function as object.keys ())
The toString\get\set attribute was not printed, but __proto__ and prototype were mixed up.
After the correction:
function A() {
console.log('I'm the function A'.)};// Define the prototype object
let protoObj = {};
protoObj = Object.defineProperty(protoObj, 'a', {
enumerable: false.// Not enumerable
value: 'a property'
});
protoObj.b = Attributes' b ';
A.prototype = protoObj;
let a = new A();
// Let... In is similar to object.keys () in that it can access enumerable properties
for (let key in a) {
console.log(key, a[key]); // b b attributes
}
Copy the code
Next check whether the toString() method in n.__proto__ mentioned in the screenshot above is enumerated
The getOwnPropertyNames method prints all properties, enumerable and non-enumerable
let res1 = Object.getOwnPropertyNames(n.__proto__);
console.log(res1);
// The result is as follows
// ["constructor", "__defineGetter__", "__defineSetter__", "hasOwnProperty", "__lookupGetter__", "__lookupSetter__", "isPrototypeOf", "propertyIsEnumerable", "toString", "valueOf", "__proto__", "toLocaleString"]
// We know that object.keys () can only access enumerable properties
let res2 = Object.keys(n.__proto__);
console.log(res2);
/ / []
Copy the code
The result is obvious: the parent method inherited from Object. Prototype is objective, callable, not enumerable, not traversal
The __proto__ attribute, in addition, is the implicit prototype of an object, pointing to the prototype of the constructor that constructed the object
console.log(a.__proto__ === A.prototype) // true
Copy the code
We’ll talk more about that later.
Ps. At the beginning of writing documents with MD grammar, I am not very skilled in using it. In the future, I will share more meaningful articles with you.