1

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 following answer might interest you http://stackoverflow.com/questions/18907888/how-to-wrap-the-jquery-function/18908560#18908560 – plalx Sep 25 '13 at 17:42

2 Answers2

3

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.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • +1 - I agree. There is no context for the myTest jQuery object when the pointer to the prototype function is passed. – Travis J Sep 25 '13 at 17:22
2

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);

Fiddle

Ehtesham
  • 2,967
  • 1
  • 18
  • 20