我有这个最小的例子,它工作正常:
var node = $('div');
var fun1 = function(filter) { return node.find(filter) };
console.log(fun1('span'));
DOM:
<div><span>text</span></div>
似乎合乎逻辑,因为我只是将参数传递给下一个函数,我可以摆脱它并简单地引用find
函数:
var node = $('div');
var fun2 = node.find;
console.log(fun2('span'));
但它会抛出Uncaught TypeError: Object [object global] has no method 'pushStack'
。
有人可以告诉我这有什么问题吗?
答案 0 :(得分:3)
当您将node
功能的引用分配给find
时,您已失去fun2
的上下文。您可以通过calling fun2
获取该背景信息:
fun2.call(node, 'span');
或者,您不必每次都这样做,bind对find
的引用回node
:
var fun2 = node.find.bind(node);
这是一个updated example。
更新(感谢Jon):如果您需要支持未实现Function.prototype.bind
的旧浏览器,您可以使用先前链接到的MDN文章中详细说明的polyfill,或使用{{3 ,它做同样的事情:
var fun2 = $.proxy(node.find, node);