如何将上下文传递给匿名函数? [英] How to pass context to anonymous function?
问题描述
有一些功能,它可以做很长时间的工作,并提供回调。
There are some function, thats do something long work and its provides callback.
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);
如何在不传递上下文的情况下实现回调函数
参数?
需要这样的:
someFunc('bla-bla', function () {
// do something with this scope
this.anotherFunc();
}, this);
推荐答案
接受的答案似乎有点过时了。假设您在相对较新的浏览器上运行,可以在 Function.prototype.bind US / docs / Web / JavaScript / Reference / Global_Objects / Function / bindrel =noreferrer> vanilla javascript 。或者,如果您使用下划线或 jQuery ,你可以使用 _。bind
或 $。proxy
分别(如果需要,将回退到致电
/ 申请
)。
The accepted answer seems somewhat outdated. Assuming you're operating on a relatively modern browser, you can use Function.prototype.bind
in vanilla javascript. Alternatively, if you are using underscore or jQuery, you can use _.bind
or $.proxy
respectively (which will fallback to call
/apply
if necessary).
以下是这三个选项的简单演示:
Here is a simple demonstration of these three options:
// 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/ (注意:确保开发者控制台已打开,否则您将看不到任何内容输出)
You can find the code in a jsfiddle here: http://jsfiddle.net/yMm6t/1/ (note: ensure that the developer console is open, or you won't see any output)
这篇关于如何将上下文传递给匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!