通过一种方法供以后评估 [英] Passing a method for later evaluation
本文介绍了通过一种方法供以后评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我将函数作为参数传递,并且该函数是jQuery方法,以后调用传递的函数是否仍会正确设置this
?我以为会,但是稍后调用该函数的是this = Window
.
If I pass a function as an argument, and the function is a jQuery method, will calling the passed function later still correctly set this
? I thought it would, but calling the function later has 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
:
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
是在旧版浏览器上不受支持(例如IE8和FF3(或更早版本).
It is worth noting bind
is not supported on older browsers (e.g. IE8 and FF3 (or older)).
这篇关于通过一种方法供以后评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文