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 badges4 Answers
Reset to default 4Now (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
版权声明:本文标题:Javascript objects and passing member functions as parameters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742040071a2417512.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论