user310291 February 2016

Why is this javascript object with simplest constructor undefined?

I tested this in console :

var toto = (function() {function toto() {}})();
toto

Result in chrome console is

undefined

Why ? I would have expected as usual the constructor :

function toto() {}

What syntax error did I make ?

Answers


Louis Ricci February 2016

You forgot a return.

var toto = (function() {return function toto() {}})();

The return'ed value is what's assigned to the variable, if you hve no return statement then the value returned is undefined.


Michael Warner February 2016

If you run this code I believe this will give you the answer.

var noname = (function() {
    function toto() {
         console.log('running toto');
         return 'returning toto';
    }
    console.log(toto());
    return 'no name';
})();
console.log(noname);

The longer answer is the following.

(function(){})();

This is called an IIFE (Immediately Invoked Function Expression) it creates and calls the function right after it is created. What you place in it, is contained to that function. This is the best way to create private variables in ES5 Javascript. Like all functions you can return things from an IIFE and access variables declared outside the IIFE but nothing within from the outside, again it creates a private scope. As you have your IIFE return nothing it returns the default value undefined.

Post Status

Asked in February 2016
Viewed 3,013 times
Voted 5
Answered 2 times

Search




Leave an answer