Have trouble with namespacing and objects. I'm new on this so really confused. I would like for one object in array to inherit parent object methods.
Here is my code:
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();
How can I inherit myfunc2 for my arr2 of objects? Is this used by prototype?
returns "Uncaught TypeError: Object [object Object] has no method 'myfunc2'"
As I see, you want to have the methods of "obj" in the objects you are creating at
this.arr2.push(new this.myfunc1(x, this.arr1[x]));
It's easy, the constructor of these objects is this.myfunct1() so you must assign the prototype object in the constructor's prototype property:
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();
And then "this" (obj) is the prototype of the created objects
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.