This is the second day of my participation in the First Challenge 2022
Hi, I am xiao 17 _, happy New Year, today is the second day of the Chinese New Year, before sorting out the JS prototype chain related knowledge, sorted out several articles, here to share with you. This article looks at how objects find properties or assign values based on stereotypes.
When objects are created in javascript, they have a default [[Prototype]] property that refers to other objects. [[Prototype]] is given a non-null value when almost all objects are created.
Reference the value of an object’s property
The default [[Get]] operation, when attempting to reference a property of an object, first looks for the property in the object itself. If not, it looks for the property in the prototype chain of the object. If not, it returns undefined.
var obj = {
a: 2
}
var res = Object.create(obj);
console.log(res.a); / / 2
Copy the code
Create creates a new Object and associates the [[Prototype]] of the new Object to the specified Object. All objects [[Prototype]] end up pointing to Object.prototype.
Assign a value to an attribute of an object
Assigning a property to an object is more than just assigning a value to the property.
myObject.foo = 'bar';
Copy the code
- If the object itself has
foo
This general data access property is modified directlyfoo
The value of the attribute - If the object itself does not
foo
Property, will find the prototype chain of the object, if the whole prototype chain is not found, thenfoo
Will be added directly tomyObject
- If the object itself does not
foo
Attribute on the prototype chain, then there are two special cases:
The first kind of
var obj = {};
Object.defineProperties(obj, {
a: {
value: 2.writable: false}});var res = Object.create(obj);
res.a = 3;
console.log(res.a); / / 2
Copy the code
Prototype chain property of the same name, writable is false, cannot be masked, strict mode will report an error.
The second:
var obj = {};
Object.defineProperties(obj, {
a: {
get: function(){
return 2; }}})console.log(obj.a); / / 2
var res = Object.create(obj);
res.a = 3;
console.log(res.a); / / 2
Copy the code
Property of the same name on the prototype chain, overrides the getter or setter, and it’s going to follow the getter and setter.
If either of these cases also want to mask attributes of the same name on the prototype chain, do not use = assignment and use Object.defineProperties
In cases other than these two, masking occurs, using newly defined properties at the bottom of the prototype chain.