I'm experimenting with higher-order functions in Javascript and I wrote up something like this:
function hof (setter) {
setter("not test");
}
function hof2 (setter) {
setter.call(window.jQuery, "not test 2");
}
var span = $("#myTest").text;
hof(span);
hof2(span);
Here's the jsFiddle version: http://jsfiddle.net/6mcYt/
However, both functions throw an error. What is the best way to pass jQuery setter functions to a higher-order function?
The text
function actually belongs on jQuery.fn
(which is also assigned to the prototype property of the jQuery constructor). If you pass that as the first argument to setter.call
, it will stop throwing an error. BUT it won't work if the desired result is changing the text on #myTest
, because you won't have any reference to the element anymore (you left that on $("#myTest")
, which is an instance of the jQuery constructor).
Sorry if I can't offer an actual solution, I'm not sure what you're trying to accomplish here.
I think what you want to do (I am not 100% sure) should be like this.
function hof ($el) {
$.fn.text.call($el, 'test1')
}
var span = $("#myTest");
hof(span);
here is the fiddle http://jsfiddle.net/6mcYt/2/
Another option is to bind the text method with context first.
function hof2 (setter) {
setter("not test 2");
}
var spanFn = $.proxy($.fn.text, $("#myTest"));
hof2(spanFn);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.