kevin
kevin

Reputation: 2213

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);
    }
}
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.

Upvotes: 2

Views: 145

Answers (3)

CD..
CD..

Reputation: 74126

Orange.prototype.onCalled=function(){
    this.apple.onCalled.call(this);
}

Example: http://jsfiddle.net/XrtZe/

Have a look at: Scope in JavaScript

Upvotes: 1

Kos
Kos

Reputation: 72261

Use a closure.

function Orange(){
    this.name="orange";

    this.apple = new Apple();
    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.

Upvotes: 4

Pointy
Pointy

Reputation: 413717

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.

Upvotes: 1

Related Questions