javascript - 传递一种方法供以后评估

标签 javascript jquery

如果我将一个函数作为参数传递,并且该函数是一个 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)); 

值得注意的是bindnot supported on older browsers (例如 IE8 和 FF3(或更早版本))。

关于javascript - 传递一种方法供以后评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32851241/

相关文章:

javascript - ajaxify-html5.js 只重新加载页面的一部分?

javascript - 在 jquery 的 mouseout 事件上关闭所有 Accordion

javascript - 从具有隔离范围的指令内的指令访问 Controller

jquery .get 页面加载不在页面顶部加载

jquery - Rangy + ContentEditable + 设置插入符和替换选择

javascript - 提取 css 并与数据属性匹配

javascript - 如何使用 Browserify 要求 vendor 脚本?

javascript - 打开附件时自动显示打印对话框

javascript - 如何读取SSL数据?

javascript - jquery replaceWith() 不更新数据