admin管理员组

文章数量:1318156

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.

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.

Share Improve this question asked Feb 16, 2012 at 2:20 user1032861user1032861 5274 gold badges11 silver badges20 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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);

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
}

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

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

本文标签: Javascript objects and passing member functions as parametersStack Overflow