javascript 如何绑定内联匿名函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24467746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:51:06 来源:igfitidea点击:
How to bind an inline anonymous function?
提问by erosman
I am trying to bind
(ie bind(this)
) the inline anonymous callback function to the object
How can it be done?
我正在尝试bind
(即bind(this)
)将内联匿名回调函数传递给object
如何完成?
Simplified example:
简化示例:
var object = {
property: function() {
this.id = 'abc'; // 'this' binds to the object
aFunctionWithCallback(this.id, function(data) {
console.log(this); // null
});
}
};
回答by Quentin
The same way you always use bind
.
与您始终使用的方式相同bind
。
Get a reference to the function (such as is returned by a function expression), and call the bind
method on it.
获取对函数的引用(例如由函数表达式返回),并调用其bind
上的方法。
aFunctionWithCallback(this.id, function(data) {
console.log(this);
}.bind(this));