简体   繁体   中英

understanding JavaScript Prototypal Inheritance

I'm reading this article about angular inheritance, and it started by JavaScript Prototypal Inheritance. the article said that when we do childScope.aString = 'child string' the new property hides/shadows the parentScope property with the same name , but when we do childScope.anArray[1] = 22 the property values are updated on the original objects. and I don't understand that.
can anyone help.
thank you in advance

ab = c explicitly assigns a value to the property b of object a . This will overwrite any and all implicitly inherited properties. Sample in actual Javascript with actual inheritance:

 function A() {} A.prototype.b = 'c'; var a = new A(); console.log(ab); 

a does not actually have a property b , it's merely inherited from the prototype. Now:

a.b = 'd';

This has now attached an actual property b directly to a . The prototype still has a property b = 'c' , but that is not visible on a anymore. ab is now 'd' .

The difference between this and a.anArray[1] = 22 is that here you're modifying a mutable object. You're not assigning to a property on a , you're getting a property from a and then modify it. This does not change a , it changes the instance of the object anArray . Which is visible to everything that has access to anArray .

Property access resolution can happen either as part of a write, or a read operation on the property. Prototypal inheritance says that only resolution as part of a read operation should involve inherited properties lookup.

Your first scenario involves a write opreation on the property - so no lookup for inherited property will occur.

In the second scenario however, the property lookup happens as part of an index lookup on the property, not a write operation on the property - ie read operation so no lookup for inherited properties

childScope.aString = 'child string'
childScope.anArray[1] = 22

1个

In the first case the assignment is being made directly to the value of the property. JavaScript adds a new property to the child scope.

In the second case the assignment is being made to the contents of the property. Since the property does not exist on the child scope, JavaScript searches the the prototype chain to find the existing contents and modifies that.

For further reading, see AngularJS Wiki -- Understanding Scopes and the Nuances of Prototypical Inheritance .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM