如何将上下文传递给匿名函数?

29

有一些函数会执行耗时操作并提供回调功能。

someFunc: function(argument, callback, context) {
  // do something long

  // call callback function
  callback(context);
}

在应用程序中我使用这个函数。

someFunc('bla-bla', function (context) {
  // do something with this scope
  context.anotherFunc();
}, this);

如何在不传递context参数的情况下实现回调函数?

需要类似这样的方法:

someFunc('bla-bla', function () {
  // do something with this scope
  this.anotherFunc();
}, this);

1
那么在你最终的例子中,似乎你正在传递上下文(至少是某个东西),你只是好奇如果参数没有命名,如何引用该参数? - Quintin Robinson
你正在传递参数,只是没有使用它。我不明白为什么。 - bfavaretto
2
@bfavaretto:OP通过将其传递到回调中来使用它,以便回调可以利用外部“this”值的方法。因此,问题是如何实现最后一个代码块...在回调中获取正确的“this”,因此不需要将其作为参数传递。 - I Hate Lazy
2个回答

43
已经接受的答案似乎有些过时了。假设您正在使用相对较新的浏览器,您可以在纯JavaScript中使用Function.prototype.bind。或者,如果您使用underscorejQuery,您可以分别使用_.bind$.proxy(如果需要,将回退到call/apply)。以下是这三个选项的简单演示:
// simple function that takes another function
// as its parameter and then executes it.
function execute_param(func) {
    func();
}

// dummy object. providing an alternative context.
obj = {};
obj.data = 10;

// no context provided
// outputs 'Window'
execute_param(function(){
    console.log(this);
});

// context provided by js - Function.prototype.bind
// src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
// outputs 'Object { data=10 }''
execute_param(function(){
    console.log(this);
}.bind(obj));

// context provided by underscore - _.bind
// src: http://underscorejs.org/#bind
// outputs 'Object { data=10 }'
execute_param(_.bind(function(){
    console.log(this);
},obj));

// context provided by jQuery - $.proxy
// src: http://api.jquery.com/jQuery.proxy/
// outputs 'Object { data=10 }'
execute_param($.proxy(function(){
    console.log(this);
},obj));

你可以在这里的jsfiddle中找到代码: http://jsfiddle.net/yMm6t/1/注意:确保开启开发者控制台,否则你将看不到任何输出

是的,现在我到处都在使用下划线 :) - acelot
@PiONeeR 是的,我也是 :) 你可能需要重新考虑哪个答案应该被接受。 - EleventyOne
你如何将 this 绑定到另一个变量名下?例如 .bind(that) - Jonathan

15

使用 Function.prototype.call 来调用一个函数并手动设置该函数的this值。

someFunc: function(argument, callback, context) {
    callback.call(context); // call the callback and manually set the 'this'
}

现在你的回调函数拥有了预期的this值。

someFunc('bla-bla', function () {
  // now 'this' is what you'd expect
    this.anotherFunc();
}, this);
当然可以像普通方式一样传递参数给.call的调用。
callback.call(context, argument);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接