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);
prototype is instance variable, you can access prototype with obj.prototypeName when you create obj with new Obj()
first see Array
Array.forEach
// undefined
Array.prototype.forEach
// ƒ forEach() { [native code] }
new Array().forEach
// ƒ forEach() { [native code] }
[].forEach
// ƒ forEach() { [native code] }
see your CT class
function CT() {}
CT.prototype.myValue = 4;
var ct1 = new CT();
var ct2 = new CT();
ct1.myValue = 100;
console.log(ct1.myValue); //logs 100
console.log(ct2.myValue); //logs 4
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.