Javascript Execution Context Of Function Argument
function Apple(){ this.name='apple'; } function Orange(){ this.name='orange'; this.apple = new Apple(); this.apple.onCalled=function(){ alert(this.name);
Solution 1:
Use a closure.
functionOrange(){
this.name="orange";
this.apple = newApple();
var that = this;
this.apple.onCalled=function() {
alert(that.name);
}
}
Have a read how keyword this
works in JS, it's a bit tricky but easy to grasp.
Solution 2:
You could write:
Orange.prototype.onCalled=function(){
this.apple.onCalled.call(this);
}
It's hard to give a general answer. The thing to understand is that this
is bound upon any function call. That can be explicitly controlled with the call
or apply
functions, or by the .
operator when accessing a function as a property of an object.
The answer Kos gives about using a closure may also be relevant; it depends on the effect you want.
Solution 3:
Orange.prototype.onCalled=function(){
this.apple.onCalled.call(this);
}
Example: http://jsfiddle.net/XrtZe/
Have a look at: Scope in JavaScript
Post a Comment for "Javascript Execution Context Of Function Argument"