在創建物件時出現 Javascript “不是建構函數” 異常
我正在這樣定義一個物件:
function Project(Attributes, ProjectWidth, ProjectHeight) {
this.ProjectHeight = ProjectHeight;
this.ProjectWidth = ProjectWidth;
this.ProjectScale = this.GetProjectScale();
this.Attributes = Attributes;
this.currentLayout = '';
this.CreateLayoutArray = function()
{....}
}
然後我嘗試像這樣創建一個實例:
var newProj = new Project(a,b,c);
但是這個例外被拋出:
Project is not a constructor
可能出了什麼問題?我上網查了很多,但我仍然無法弄清楚我做錯了什麼。
答案#1
如問題中所貼出的程式碼無法產生該錯誤,因為 Project 不是使用者定義的函數/有效的建構子。
function x(a,b,c){}
new x(1,2,3); // produces no errors
你可能做過類似這樣的事情:
function Project(a,b,c) {}
Project = {}; // or possibly Project = new Project
new Project(1,2,3); // -> TypeError: Project is not a constructor
使用 var 的變數宣告會被提升,因此總是在其餘程式碼之前被評估。所以,這也可能引起問題:
function Project(){}
function localTest() {
new Project(1,2,3); // `Project` points to the local variable,
// not the global constructor!
//...some noise, causing you to forget that the `Project` constructor was used
var Project = 1; // Evaluated first
}
答案#2
這個問題的另一個原因可能是 ES2015 箭頭函數。它們不能被用作建構函數。
const f = () => {};
new f(); // This throws "f is not a constructor"
答案#3
對我來說,是 ES6 中 import 和 require 之間的差異。
例如
processor.js
class Processor {
}
export default Processor
index.js
const Processor = require('./processor');
const processor = new Processor() //fails with the error
import Processor from './processor'
const processor = new Processor() // succeed
答案#4
我也在谷歌上查過,找到了這個解決方案:
你在某處有一個變數 Project,它不是一個函數。然後 new 運算符會對此發出錯誤。在你打算用它作為構造函數的地方試試 console.log(Project),你就會發現問題所在。
答案#5
對於我的專案,問題結果是由 require() 調用創建的循環引用:
y.js:
var x = require("./x.js");
var y = function() { console.log("result is " + x(); }
module.exports = y;
x.js:
var y = require("./y.js");
var my_y = new y(); // <- TypeError: y is not a constructor
var x = function() { console.log("result is " + my_y; }
module.exports = x;
原因是當它嘗試初始化 y 時,它在依賴系統中創建了一個臨時的「y」對象(不是類,是對象!),此對象在某種程度上還不是一個構造函數。然後,當 x.js 定義完成時,它可以繼續將 y 變成一個構造函數。只是,x.js 中有一個錯誤,它試圖使用這個非構造函數的 y。
答案#6
我有一個類別在一個檔案中,我正將它匯入到一個測試檔案中:
//Vec.js
class Vec {
}
module.exports.Vec = Vec;
更改
//Vec.test.js
const Vec = require('./Vec');
const myVec = new Vec(); //TypeError: Vec is not a constructor
到
//Vec.test.js
const {Vec} = require('./Vec');
const myVec = new Vec(); //Succeeds!
為我解決了這個錯誤。
答案#7
在我的情況下,我使用原型名稱作為物件名稱。例如。
function proto1()
{}
var proto1 = new proto1();
這是一個愚蠢的錯誤,但可能對像我這樣的人有幫助 ;)
