Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  152] [ 7]  / answers: 1 / hits: 16648  / 11 Years ago, mon, november 25, 2013, 12:00:00

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!


More From » function

 Answers
28

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.


[#74077] Saturday, November 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patienceannel

Total Points: 674
Total Questions: 101
Total Answers: 101

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
patienceannel questions
Fri, Mar 11, 22, 00:00, 2 Years ago
Tue, Oct 20, 20, 00:00, 4 Years ago
Wed, Jul 24, 19, 00:00, 5 Years ago
;