I'm learning JS. Kyle Simpson in his Book, YDKJS, writes that:
If a normal data accessor (see Chapter 3) property named foo is found anywhere higher on the [[Prototype]] chain, and it's not marked as read-only ( writable:true) then a new property called foo is added directly to myObject , resulting in a shadowed property.
function Foo(name) {
this.name = name;
}
Foo.prototype.myName = function() {
return this.name;
};
var a = new Foo( "a" );
var b = new Foo( "b" );
In the above snippet, it's strongly tempting to think that when a and b are created, the properties/functions on the Foo.prototype object are copied over to each of a and b objects. However, that's not what happens. When
myNameis not found on a or b , respectively, it's instead found (through delegation, see Chapter 6) on Foo.prototype . Reference Page 97
To test the same, I created a property val on prototype object with value 1:
Foo.prototype.val = 1;
Since object a is prototype linked, I incremented this property by 1:
a.val++;
But when I executed following two lines:
console.log(a.val);
console.log(Foo.prototype.val);
Result:
2
1
The result shows that a separate property val is created on object a with the incremented value 2, which seems contradicts (that its delegated) with his statement.
Where did I astray? Please guide
I think you may be confusing what happens with values on the prototype when assigning a value vs when creating an object using the constructor function.
For example, take the book's first example:
As Kyle outlines in his book, when using the
newkeyword to create objectsaandb, the values fromFoo.prototypearen't created as properties directly onaandb(ie: own-properties), but instead,aandb's[[Prototype]]s point toFoo.prototype, which is wheremyNameis accessed.In your example code, you're firstly creating a property called
valon the prototype:and then incrementing
val. This increment is what then creates an own-property ona. To show what's happening in more detail, the below is begin performed:The
a.val =component of the above creates an own property calledvaldirectly on theaobject, and thea.val + 1is accessing the value you had previously set withFoo.prototype.val = 1;via accessingavia the[[Prototype]], and then adding1to it. As you're effectively doing an "assignment" here, you end up creating an own property ona, which is a different operation from what the excerpt shown from Kyle's book is doing, where he is just creating a new object using thenewkeyword.