Why is my JS, which should return an object, return undefined?

Well, since I understand my code, I created a promoSlides object, I have a private function called init, and as a result of returning the js-closure (which I am not very familiar with) I returned init, so I can use it outside the global view. When I run the file, I get promoSlides undefined, says the FF error console. I do not know where I was wrong. I am new to this, so maybe something is wrong. Oh, and the slides were defined in my original document, but I took it for simplicity

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); }); 
+4
source share
3 answers

Reinstall semicolons again!

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

should be

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

This is the result of a “function” in JavaScript that looks at your string using 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 bare JSON sitting over it, which is the source of your error. Douglas Crockford actually describes this as one of the “terrible parts” of JavaScript.

So, the moral of this story is: always put your open shape on the same line when you code in JavaScript.

+4
source

Your problem is the deadly "supposed semicolon" in the return line:

 return //; <-- Javascript puts an implicit EOL here { init : function a(s) { init(s); } }; 

Change to

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

and your code should work.

+4
source

The problem with the supposed semicolon has already been described above. But do not use so many function calls!

 var init = function() { ... }; return { init : init }; 

works and even shorter:

 var slides; // unused variable ??? return { init: function init(s) { slides = s; sortSlides(); startTimer(); addListeners(); } } 
0
source

Source: https://habr.com/ru/post/1382770/


All Articles