4

This is hard to explain, maybe it's better if I write some sample code:

function A()
{
    this.b = new B();

    this.a_value = 456;

    this.f = function(i)
    {
        for(var i = 0; i < this.a_value; ++i)
            DoStuff(i);
    }

    this.b.C(this.f)
}

I'm trying to pass a function as an argument to B, but when C tries to reach a_value it's undefined. How do I fix it?

I hope I didn't oversimplify my problem.

4 Answers 4

4

Now (or since 2015 apparently), you can also bind the function to the object instance as shown in this answer:

this.b.C(this.f.bind(this));

By way of an explanation:

var fn = myObject.myFunction.bind(myObject);

// The following two function calls are now equivalent
fn(123);
myObject.myFunction(123);
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer! The other answers resort to using a random named variable to store this, which works, but is not very maintainable in a big long-lived code-base
2

You ca pass this.f to function c, but to call it properly, you need to also pass the value of this like this:

function A()
{
    this.b = new B();

    this.a_value = 456;

    this.f = function(i)
    {
        for(var i = 0; i < this.a_value; ++i)
            DoStuff(i);
    }

    this.b.C(this.f, this)   // <== pass "this" here
}

And, then in `this.b.c`:

...b.c = function(fn, context) {
   fn.call(context);      // <== use .call() here to apply the right this value
}

Comments

1

The problem is that this isn't bound to any fixed value in JavaScript. You can use a closure to fix this, and it's probably the best way in this case:

function A()
{
    var that = this;

    this.b = new B();

    this.a_value = 456;

    this.f = function(i)
    {
        for(var i = 0; i < that.a_value; ++i)
            DoStuff(i);
    }

    this.b.C(this.f);
}

Comments

1

Yet another way of achieving the same thing using an arrow function. Since arrow functions do not bind this it will retain whatever value it had when the function was defined.

function A()
{
    this.b = new B();

    this.a_value = 456;

    this.f = i =>
    {
        for(var i = 0; i < this.a_value; ++i)
            DoStuff(i);
    }

    this.b.C(this.f)
}

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.