【发布时间】: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 属性?
-
当然可以,如果您对属性进行原型制作,而不仅仅是将它们附加到对象上。这就是为什么我们要继承原型(至少是其中一个原因)。