在 javascript 中使用 Object.create(someprototype) 创建的对象的构造函数

Constructor of the object created using Object.create(someprototype) in javascript

使用 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

那是因为你还没有调用构造函数

考虑以下因素:

barObj.constructor(); // <--- this will call the constructor function and set this.name1 and this.otherName1
console.log(barObj.name1); // Outputs: "Name"

这里 barObj 只是一个链接到 foo 原型对象的对象。Object.create 不会调用 foo 函数,除非您显式调用它。请参阅下面的代码。

foo.call(barObj) 将使用 barObj 作为上下文调用 foo 函数。表示 thisfoo 函数中引用 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);