2

使用 Object.create(someObj.prototype) 创建的对象的构造函数为 someObj,那么当我尝试访问 someObj 的属性时,怎么会出现未定义?

function foo(){
    this.name1 = "Name";
    this.otherName1 = "someOtherName";
}

var fooObj = new foo();
console.log(fooObj.name1); // Name

var barObj = Object.create(foo.prototype);

console.log(barObj.constructor);  
   //Outouts: 
  // function foo(){
 //    this.name1 = "Name";                                                                                                         

 //      this.otherName1 = "someOtherName" ;
//    }


//Then why not able to access this?
console.log(barObj.name1); Outputs; // undefined
4

2 回答 2

3

这只是因为你还没有调用构造函数。

考虑以下:

barObj.constructor(); // <--- this will call the constructor function and set this.name1 and this.otherName1
console.log(barObj.name1); // Outputs: "Name"
于 2015-12-03T20:47:48.193 回答
0

这里barObj只是一个链接到 foo 原型对象的对象。Object.create在您明确调用它之前不会调用 foo 函数。请参见下面的代码。

foo.call(barObj)将调用 foo 函数, barObj因为它是上下文。意味着foo函数中的this指的是.barObj

function foo(){
    this.name1 = "Name";
    this.otherName1 = "someOtherName";
}

var fooObj = new foo();
//console.log(fooObj); // Name

var barObj = Object.create(foo.prototype);
foo.call(barObj)

//Outouts: 
// function foo(){
//  this.name1 = "Name";                                                                                                         

//  this.otherName1 = "someOtherName" ;
//}


//Then why not able to access this?
console.log(barObj.name1);
于 2016-01-14T15:59:12.313 回答