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

ace*_*lot 28 javascript callback

有一些功能,可以做很长时间的工作,并提供回调.

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

  // call callback function
  callback(context);
}
Run Code Online (Sandbox Code Playgroud)

在应用程序中我使用此功能

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

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

需要这样的:

someFunc('bla-bla', function () {
  // do something with this scope
  this.anotherFunc();
}, this);
Run Code Online (Sandbox Code Playgroud)

Ele*_*One 40

接受的答案似乎有点过时了.假设你在一个比较现代的浏览器操作,您可以使用Function.prototype.bind香草的JavaScript.或者,如果您使用下划线jQuery,则可以分别使用_.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));
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到jsfiddle中的代码:http://jsfiddle.net/yMm6t/1/(注意:确保开发人员控制台已打开,否则您将看不到任何输出)


I H*_*azy 14

使用Function.prototype.call调用功能和手动设置this该函数的值.

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

现在您的回调具有预期this值.

someFunc('bla-bla', function () {
  // now 'this' is what you'd expect
    this.anotherFunc();
}, this);
Run Code Online (Sandbox Code Playgroud)

当然,您可以在.call调用中传递正常的参数.

callback.call(context, argument);
Run Code Online (Sandbox Code Playgroud)