Reputation: 4258
I have a class, and have given its prototype several sub-objects to facilitate namespacing. These sub-objects have methods. I can't figure out how to use this
inside those methods to access the properties set with the constructor.
I have a feeling bind
, call
, and apply
are involved somehow, but I'm having a good deal of trouble understanding what those do, and how all this OOP-ness works in general. There are plenty of resources, but they're all either too low-level, or so high-level I don't understand them. Thank you!
function Object(
argument1,
argument2
){
this.property1 = argument1;
this.property2 = argument2;
}
Object.prototype = {
subObject1 : {
method1 : function(){
return this.property1;
}
},
subObject2 : {
method1 : function(){
return this.property2;
}
}
}
var foo = new Object(11, 22);
var bar = new Object(33, 44);
console.log(foo.subObject1.method1()); //I'd like this to return 11
console.log(foo.subObject2.method1()); //I'd like this to return 22
console.log(bar.subObject1.method1()); //I'd like this to return 33
console.log(bar.subObject2.method1()); //I'd like this to return 44
Upvotes: 3
Views: 1167
Reputation: 816334
Whenever you have a call of the form foo.bar()
, this
inside bar
will refer to foo
. Unless you bind the the function to a specific value with .bind
, or use the new "arrow" functions in ES6.
So one solution could be to bind the methods to the specific instance. However, the instance doesn't exist until you call the constructor function. That means you have to create subObjectX
inside the constructor:
function MyObject(argument1, argument2) {
this.property1 = argument1;
this.property2 = argument2;
this.subObject1 = {
method1: function(){
return this.property1;
}.bind(this)
};
this.subObject2 = {
method1: function(){
return this.property2;
}.bind(this)
};
}
Or using the new ES6 arrow functions; these take this
from the context in which they're created (unlike normal functions):
// ES6 only!
function MyObject(argument1, argument2) {
this.property1 = argument1;
this.property2 = argument2;
this.subObject1 = {
method1: () => {
return this.property1;
}
};
this.subObject2 = {
method1: () => {
return this.property2;
}
};
}
That means that every instance has it's own copy of the sub-object.
If you want to define the methods on the prototype though, you always have to pass the receiver via .call
or .apply
:
foo.subObject1.method1.call(foo);
in which case there is not much benefit of assigning it to the prototype at all, and you could just have a simple function that accept the object (method1(foo)
).
Upvotes: 5