简体   繁体   English

原型和TypeError:someFunction不是构造函数

[英]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. 我有一个关于原型,变量声明和构造函数的Javascript行为问题。

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; 答案 :以下答案表明,在第二种情况下,我们没有使用function关键字初始化var myFunction rather we are only returning a JSON object with a property named method which results into an error when executing var obj = new myFunction(); 相反,我们只返回一个带有名为method的属性的JSON对象,当执行var obj = new myFunction();时,该对象会导致错误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 如果我们去除IIFE和局部变量,则您的第一个代码段将变为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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