2012-02-16 80 views
3

这是很难解释的,也许是更好的,如果我写的一些示例代码:JavaScript对象和传递成员函数参数

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

我想传递一个函数作为参数传递给B,但是当C尝试达到a_value它是未定义的。我如何解决它?

我希望我没有过分简化我的问题。

回答

1

问题是this没有绑定到JavaScript中的任何固定值。您可以使用闭合来解决这个问题,而且它可能在这种情况下,最好的办法:

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

您CA传递this.f运作c,但正确地调用它,你也需要传递的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 
} 
1

现在(或自2015年显然),也可以在功能结合到对象实例如图in this answer

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

通过的解释道:

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

// The following two function calls are now equivalent 
fn(123); 
myObject.myFunction(123); 
0

另一个用箭头功能实现同样的事情的方式。由于箭头函数不绑定this它将保留函数定义时所具有的值。

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) 
} 
相关问题