简体   繁体   中英

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"?

ie 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 (eg orange.name) but I'm looking for a better way because there are many objects and I don't want to global everything.

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.

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.

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

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

Have a look at: Scope in JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM