As we know, when we try to access an object's property it first check's if the object has its own property. If it does not find, it traverses the prototype and checks, and so on up the prototype chain.
Coming to the question, please check the below code snippet(http://jsbin.com/mabajidoti/edit?js,console)
function CT() {}
CT.prototype.myValue = 4;
var myObj = Object.create(CT);
console.log(myObj.myValue); //logs undefined
console.log(myObj.prototype.myValue) //logs 4
From the above snippet, the first console.log statement, myObj.myValue is returning undefined even though myValue is available in its prototype(2nd console.log statement)? Shouldn't it have traversed the prototype chain to fetch the myValue's value?
You seem to have confused
Object.create()with calling a constructor function via thenewoperator.If you'd said:
then your
myObjwould be linked to theCT.prototypeand thusmyObj.myValuewould be4.But by using
Object.create(CT)you've created a new object whose prototype is theCTfunction itself. SoCT.prototypeis not part of your new object's prototype chain. Note thatCT.prototypeisn't inCT's prototype chain, rather, it specifies the object that will be the prototype for things created withnew CT().A more correct use of
Object.create()to allow access to amyValueproperty from the prototype would be:Or with your existing
CT()function andCT.prototypeyou could say: