d0c_s4vage
d0c_s4vage

Reputation: 4077

IE10 Javascript "Function Expected"

This code is giving me a SCRIPT5002: Function expected error:

var callIt = function(func) { func(); }

WHY!? It's like it's trying to do type checking or something

EDIT: use case

var callIt = function(func) { func(); }
function nextSlide() {
    var fn = currSlide ? currSlide.hide : callIt;
    currSlide = setupSlides[++slideIdx];
    fn(currSlide.show());
}

DOH!

Upvotes: 4

Views: 17037

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074108

Your code:

fn(currSlide.show());

...calls currSlide.show() and passes the return value from calling it into fn, exactly the way foo(bar()) calls bar and passes its return value into foo.

since the return value of show is not a function, you get the error. You may have meant:

fn(function() { currSlide.show(); });

Note, though, that you have a problem here:

var fn = currSlide ? currSlide.hide : callIt;

If currSlide is truthy, you'll get a reference to the hide function, but that function is not in any way connected to currSlide. If you call it later, it's likely to fail because it's expecting this to mean something specific.

If you can rely on having the features from ECMAScript5 (so, you're using a modern browser other than IE8 and/or you're including an "es5 shim", you can fix that with Function#bind:

var fn = currSlide ? currSlide.hide.bind(currSlide) : callIt;

Or if you're using jQuery, you can fix it with jQuery's $.proxy:

var fn = currSlide ? $.proxy(currSlide.hide, currSlide) : callIt;

Both of those return a new function that, when called, will call the target function with the given this value.

If you're not using ES5 or jQuery, well, this would do it:

var prevSlide = currSlide;
var fn = prevSlide ? function(func) { prevSlide.hide(func); } : callIt;

...but at that point I suspect stepping back and reevaluating might be in order.

Upvotes: 8

Related Questions