Johan
Johan

Reputation: 3819

Prototype and TypeError: someFunction is not a constructor

I have got a question about the behaviour of Javascript with respect to prototypes, variables declarations and constructors.

Why this works:

var myFunction = function(){ alert('something')};
myFunction.prototype = (function() { 
                                     var a='something else'; 
                                     return {method:a} 
                                   } () );
var obj = new myFunction();
console.log(obj.method); // the message 'something else' is logged

whereas this does not work:

var myFunction = (function() { 
                              var a='something else'; 
                              return {method:a} 
                              } () );
var obj = new myFunction();
console.log(obj.method);

it throws:

Uncaught TypeError: myFunction is not a constructor(…)

ANSWER: the below answer revealed that in the second case we are not initializing var myFunction with the function keyword; rather we are only returning a JSON object with a property named method which results into an error when executing var obj = new myFunction();.

Upvotes: 0

Views: 279

Answers (1)

Bergi
Bergi

Reputation: 665574

No, this has nothing to do with hoisting. If we strip away the IIFE and the local variable, your first snippet becomes

var myFunction = function() {
    alert('something');
};
myFunction.prototype = {
    method: 'something else'
};
var obj = new myFunction();
console.log(obj.method);

whereas the second one becomes

var myFunction = {
    method: 'something else'
};
var obj = new myFunction();
console.log(obj.method);

which quite obviously cannot work.

Maybe you intended to write

var obj = (function() { 
    var a = 'something else'; 
    return {method:a} 
}());
console.log(obj.method); // the message 'something else' is logged

Upvotes: 2

Related Questions