javascript - Why is this jQuery code written in functional style doesn't work? -
i have minimal example, , works fine:
var node = $('div'); var fun1 = function(filter) { return node.find(filter) }; console.log(fun1('span')); dom:
<div><span>text</span></div> it seems logical, i'm passing argument next function, can rid of , refer find function:
var node = $('div'); var fun2 = node.find; console.log(fun2('span')); but throws uncaught typeerror: object [object global] has no method 'pushstack'.
could tell me what's wrong this?
live demo: http://jsfiddle.net/wyvhw/
you have lost context of node when assigned reference find function fun2. can context calling fun2 it:
fun2.call(node, 'span'); or, don't have every time, bind reference find node:
var fun2 = node.find.bind(node); here's updated example.
update (thanks jon): if need support old browsers don't implement function.prototype.bind can either use polyfill detailed on mdn article linked previously, or use jquery.proxy, same thing:
var fun2 = $.proxy(node.find, node);
Comments
Post a Comment