2
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.

2
  • Members of this have nothing to do with variables. In JS, this has nothing to do with variable scope. Also, you're not passing any functions in your code. Commented Jul 2, 2012 at 16:45
  • The object that "specified" the function then. In other scenarios I'm passing a callback function that's executed when something is finished, which I believe can be solved by the same solution. Commented Jul 2, 2012 at 16:55

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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

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

Have a look at: Scope in JavaScript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.