Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my JS that's supposed to return an object return undefined?

Ok so as I understand my code, I created a promoSlides object, I a private function called init and in the return of a js closure (which I am not too familiar with) I returned init so I can use it outside globally kind of. When I run the file I get promoSlides is undefined, says error console of FF. I am not sure where I went wrong. I am new to this so probably something is wrong. Oh and slides was defined in my original doc but I took it out for simplicity sake

var Slider = (function (name) {return name;}(Slider || {}));

Slider.promoSlides = ( function()
{
var slides;

var init = function(s)
{
    slides = s;
    sortSlides();
    startTimer();
    addListeners();
};
return 
{
    init : function a(s)
    {
        init(s);
    }
};

})();

$(document).ready(function(){
    Slider.promoSlides.init(slides);
});
like image 386
Huangism Avatar asked Feb 23 '23 07:02

Huangism


1 Answers

Semicolon insertion strikes again!

return 
{
    init : function a(s)
    {
        init(s);
    }
};

needs to be

return {
    init : function a(s)
    {
        init(s);
    }
};

This is a result of a "feature" in JavaScript that looks at your line with just return on it, and says: "oh, you forgot your semicolon, I'll add it for you."

It changes return to return; so your function now returns undefined, and then you have some naked JSON sitting below it, which is the source of your error. Douglas Crockford actually describes this as one of the "awful parts" of JavaScript.

So the moral of the story is: always put your opening brace on the same line when you're coding in JavaScript.

like image 63
Adam Rackis Avatar answered May 01 '23 01:05

Adam Rackis