简体   繁体   English

为什么用功能样式编写的jQuery代码不起作用?

[英]Why is this jQuery code written in functional style doesn't work?

I have this minimal example, and it works fine: 我有这个最小的示例,它工作正常:

var node = $('div');
var fun1 = function(filter) { return node.find(filter) };
console.log(fun1('span'));

DOM: DOM:

<div><span>text</span></div>

It seems logical, that as I'm only passing the argument to the next function, I can get rid of it and simply refer to the find function: 似乎合乎逻辑,因为我只将参数传递给下一个函数,所以我可以摆脱它,而只需引用find函数:

var node = $('div');
var fun2 = node.find;
console.log(fun2('span'));

But it throws Uncaught TypeError: Object [object global] has no method 'pushStack' . 但是它抛出Uncaught TypeError: Object [object global] has no method 'pushStack'

Could somebody tell me what's wrong with this? 有人可以告诉我这是怎么回事吗?

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

You have lost the context of node when you assigned a reference to the find function to fun2 . 当您将对find函数的引用分配给fun2时,您已经失去了node的上下文。 You can get that context back by calling fun2 with it: 您可以通过调用 fun2来获得该上下文:

fun2.call(node, 'span');

Or, so you don't have to do that every time, bind the reference to find back to node : 或者,因此您不必每次都这样做,请绑定引用以findnode

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

Here's an updated example . 这是一个更新的示例

Update (thanks Jon ): If you need to support old browsers that don't implement Function.prototype.bind you can either use the polyfill detailed on the MDN article linked to previously, or use jQuery.proxy , which does the same thing: 更新(感谢Jon ):如果您需要支持未实现Function.prototype.bind旧浏览器,则可以使用前面链接的MDN文章中详细介绍的jQuery.proxy ,也可以使用jQuery.proxy来完成相同的工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM