【问题标题】:Constructor of the object created using Object.create(someprototype) in javascript在 javascript 中使用 Object.create(someprototype) 创建的对象的构造函数
【发布时间】:2015-12-03 20:38:57
【问题描述】:

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

【问题讨论】:

  • this.name1 是直接附加到对象的属性,而不是原型,这就是它未定义的原因,因为它应该是
  • 我明白你的意思,是否意味着使用 Object.create() 创建的对象甚至无法访问它的 constructors 属性?
  • 当然可以,如果您对属性进行原型制作,而不仅仅是将它们附加到对象上。这就是为什么我们要继承原型(至少是其中一个原因)。

标签: javascript object-create


【解决方案1】:

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

考虑以下几点:

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

【讨论】:

  • 啊哈,有道理。
  • 总结一下:Object.create() 没有调用构造函数,因此构造函数属性没有被初始化。因此未定义的属性,对吧?在这种情况下,让我们假设,如果我创建 var y = Object.create(foo); 将调用构造函数,或者它将如何工作?或者 Object.create() 是否应该始终采用 Object.create(foo.prototype) 的形式。谢谢。
  • Object.create(); 将创建该对象的副本,这意味着它将继承该对象的原型。现在你有一个变量来保存你刚刚创建的这个新对象,所以如果你想初始化它,你需要调用构造函数。这类似于您在调用new 时初始化foo 的方式。
  • @nitte93user3232918:不,Object.create 不调用任何东西,它只是创建一个新的空对象,它继承自作为参数传递的对象。在您的情况下,barObjfoo.prototype 对象继承 .constructor 属性。
  • @Bergi 我的解释一定不是很清楚 - 谢谢你的澄清。我的意思是create() 创建了foo 的副本,因为他将其作为参数传递
【解决方案2】:

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

foo.call(barObj) 将使用barObj 调用 foo 函数,因为它是上下文。表示 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    相关资源
    最近更新 更多