![](/img/trans.png)
[英]Prototypal Inheritance Why Does Child Object Not Inherit Method From Parent Object?
[英]Namespacing inherit method of parent object
在命名空间和对象方面遇到麻烦。 我对此很陌生,真的很困惑。 我希望数组中的一个对象继承父对象方法。
这是我的代码:
var obj = {
arr1:['one', 'two'],
arr2:[],
init:function() {
for(var x=0; x<this.arr1.length; x++) {
this.arr2.push(new this.myfunc1(x, this.arr1[x]));
}
this.arr2[0].myfunc2();
},
myfunc1:function(x, name) {
this.index = x;
this.name = name;
},
myfunc2:function() {
alert(this.index + ' ' + this.name);
}
};
obj.init();
如何为对象的arr2继承myfunc2? 这是原型使用的吗?
返回“未捕获的TypeError:对象[object Object]没有方法'myfunc2'”
如我所见,您想要在创建对象的对象中使用“ obj”方法
this.arr2.push(new this.myfunc1(x, this.arr1[x]));
这很容易,这些对象的构造函数是this.myfunct1(),因此您必须在构造函数的prototype属性中分配原型对象:
this.myfunct1.prototype = this;
for(var x=0; x<this.arr1.length; x++) {
this.arr2.push(new this.myfunc1(x, this.arr1[x]));
}
// WORKS!!!
this.arr2[0].myfunc2();
然后“ this”(obj)是所创建对象的原型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.