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 the new
operator.
If you'd said:
var myObj = new CT();
then your myObj
would be linked to the CT.prototype
and thus myObj.myValue
would be 4
.
But by using Object.create(CT)
you've created a new object whose prototype is the CT
function itself. So CT.prototype
is not part of your new object's prototype chain. Note that CT.prototype
isn't in CT
's prototype chain, rather, it specifies the object that will be the prototype for things created with new CT()
.
A more correct use of Object.create()
to allow access to a myValue
property from the prototype would be:
var CT = {
myValue : 4
};
var myObj = Object.create(CT);
console.log(myObj.myValue); //logs 4
Or with your existing CT()
function and CT.prototype
you could say:
myObj = Object.create(CT.prototype);