如果我将一个函数作为参数传递,并且该函数是一个 jQuery 方法,稍后调用传递的函数是否仍会正确设置 this
?我以为会,但稍后调用该函数有 this = Window
。
示例代码:
var $input = $('input').first();
var evaluators = [];
evaluators.push($input.val);
_.forEach(evaluators, function(valueMethod) {
return valueMethod() //returns undefined always since this = window
}).
最佳答案
尝试使用 bind
:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
evaluators.push($input.val.bind($input));
值得注意的是bind
是not supported on older browsers (例如 IE8 和 FF3(或更早版本))。
关于javascript - 传递一种方法供以后评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32851241/