简体   繁体   中英

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(); .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM