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)
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…