为什么用函数式编写的这个jQuery代码不起作用?

时间:2013-08-16 10:59:51

标签: javascript jquery functional-programming

我有这个最小的例子,它工作正常:

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'

有人可以告诉我这有什么问题吗?

现场演示:http://jsfiddle.net/wyVhW/

1 个答案:

答案 0 :(得分:3)

当您将node功能的引用分配给find时,您已失去fun2的上下文。您可以通过calling fun2获取该背景信息:

fun2.call(node, 'span');

或者,您不必每次都这样做,bindfind的引用回node

var fun2 = node.find.bind(node);

这是一个updated example

更新(感谢Jon):如果您需要支持未实现Function.prototype.bind的旧浏览器,您可以使用先前链接到的MDN文章中详细说明的polyfill,或使用{{3 ,它做同样的事情:

var fun2 = $.proxy(node.find, node);