function Apple(){
this.name="apple";
}
function Orange(){
this.name="orange";
this.apple = new Apple();
this.apple.onCalled=function(){
alert(this.name);
}
}
Orange.prototype.onCalled=function(){
this.apple.onCalled();
}
var orange = new Orange();
orange.onCalled();
Currently the code shows "apple". How can I modify the "this.apple.onCalled=function()" line so that it shows "orange"?
i.e. I want to pass a function to another object, but when that function is called, access variables of the object who passed the function, not the variables of the object who is executing the function. An obvious solution would be to use global variables (e.g. orange.name) but I'm looking for a better way because there are many objects and I don't want to global everything.
thishave nothing to do with variables. In JS,thishas nothing to do with variable scope. Also, you're not passing any functions in your code.