![](/img/trans.png)
[英]someFunction.Prototype.constructor vs someFunction.constructor
[英]Prototype and TypeError: someFunction is not a constructor
我有一個關於原型,變量聲明和構造函數的Javascript行為問題。
工作原理:
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
但這不起作用:
var myFunction = (function() {
var a='something else';
return {method:a}
} () );
var obj = new myFunction();
console.log(obj.method);
它拋出:
Uncaught TypeError: myFunction is not a constructor(…)
答案 :以下答案表明,在第二種情況下,我們沒有使用function
關鍵字初始化var myFunction
; 相反,我們只返回一個帶有名為method
的屬性的JSON對象,當執行var obj = new myFunction();
時,該對象會導致錯誤var obj = new myFunction();
。
不,這與起吊無關。 如果我們去除IIFE和局部變量,則您的第一個代碼段將變為
var myFunction = function() {
alert('something');
};
myFunction.prototype = {
method: 'something else'
};
var obj = new myFunction();
console.log(obj.method);
而第二個成為
var myFunction = {
method: 'something else'
};
var obj = new myFunction();
console.log(obj.method);
這顯然是行不通的。
也許你打算寫
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.