1

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?

4

2 回答 2

2

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);
于 2017-11-04T05:47:48.463 回答
0

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
于 2017-11-04T05:52:33.980 回答