Javascript 创建对象时Javascript“不是构造函数”异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10107198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript "Not a Constructor" Exception while creating objects
提问by unni
I am defining an object like this:
我正在定义一个这样的对象:
function Project(Attributes, ProjectWidth, ProjectHeight)
{
this.ProjectHeight = ProjectHeight;
this.ProjectWidth = ProjectWidth;
this.ProjectScale = this.GetProjectScale();
this.Attributes = Attributes;
this.currentLayout = '';
this.CreateLayoutArray = function()
{....}
}
I then try to create and instance like this:
然后我尝试像这样创建和实例:
var newProj = new Project(a,b,c);
But this execption is thrown:
但是这个 exection 被抛出:
Project is not a constructor
What could be wrong? I googled around a lot, but still can't figure out what I am doing wrong.
可能有什么问题?我用谷歌搜索了很多,但仍然无法弄清楚我做错了什么。
采纳答案by Rob W
The code as posted in the question cannot generate that error, because Project
is not a user-defined function / valid constructor.
问题中发布的代码无法生成该错误,因为Project
它不是用户定义的函数/有效的构造函数。
function x(a,b,c){}
new x(1,2,3); // produces no errors
You've probably done something like this:
你可能做过这样的事情:
function Project(a,b,c) {}
Project = {}; // or possibly Project = new Project
new Project(1,2,3); // -> TypeError: Project is not a constructor
Variable declarations using var
are hoistedand thus always evaluated before the rest of the code. So, this can also be causing issues:
变量声明 usingvar
被提升,因此总是在代码的其余部分之前进行评估。因此,这也可能导致问题:
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
}
回答by wprl
An additional cause of this can be ES2015 arrow functions. They cannot be used as constructors.
另一个原因可能是 ES2015箭头函数。 它们不能用作构造函数。
const f = () => {};
new f(); // This throws "f is not a constructor"
回答by Richard Nienaber
For me it was the differences between import
and require
on ES6.
对我来说,这是ES6import
和require
ES6之间的差异。
E.g.
例如
// 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() // succeeds
回答by Bergi
I've googled around also and found this solution:
我也用谷歌搜索并找到了这个解决方案:
You have a variable Project
somewhere that is not a function. Then the new
operator will complain about it. Try console.log(Project)
at the place where you would have used it as a construcotr, and you will find it.
您在Project
某处有一个不是函数的变量。然后new
运营商会抱怨它。console.log(Project)
在您将其用作构造器的地方尝试一下,您会找到它。
回答by Edwin Hoogerbeets
For my project, the problem turned out to be a circular reference created by the require() calls:
对于我的项目,问题原来是由 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;
The reason is that when it is attempting to initialize y, it creates a temporary "y" object (not class, object!) in the dependency system that is somehow not yet a constructor. Then, when x.js is finished being defined, it can continue making y a constructor. Only, x.js has an error in it where it tries to use the non-constructor y.
原因是当它试图初始化 y 时,它在依赖系统中创建了一个临时的“y”对象(不是类,对象!),它在某种程度上还不是构造函数。然后,当 x.js 定义完成时,它可以继续制作 ya 构造函数。只是,x.js 在它尝试使用非构造函数 y 的地方有一个错误。
回答by Jiten
In my case I was using the prototype name as the object name. For e.g.
就我而言,我使用原型名称作为对象名称。例如
function proto1()
{}
var proto1 = new proto1();
It was a silly mistake but might be of help to someone like me ;)
这是一个愚蠢的错误,但可能对像我这样的人有所帮助;)
回答by Geoff Langenderfer
I have a class in one file that I'm importing into a test file:
我在一个文件中有一个类,我要导入到测试文件中:
//Vec.js
class Vec {
}
module.exports.Vec = Vec;
Changing
改变
//Vec.test.js
const Vec = require('./Vec');
const myVec = new Vec(); //TypeError: Vec is not a constructor
to
到
//Vec.test.js
const {Vec} = require('./Vec');
const myVec = new Vec(); //Succeeds!
resolved this error for me.
为我解决了这个错误。
回答by S.Norrbj?rk
I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with
我只想补充一点,如果构造函数是从不同的文件调用的,那么就像忘记导出构造函数一样简单
module.exports = NAME_OF_CONSTRUCTOR
will also cause the "Not a constructor" exception.
也会导致“不是构造函数”异常。
回答by alex351
Sometimes it is just how you export and import it. For this error message it could be, that the defaultkeyword is missing.
有时,这只是您导出和导入它的方式。对于此错误消息,可能是缺少default关键字。
export default SampleClass {}
Where you instantiate it:
在哪里实例化它:
import SampleClass from 'path/to/class';
let sampleClass = new SampleClass();
Option 2, with curly braces:
选项 2,带花括号:
export SampleClass {}
import { SampleClass } from 'path/to/class';
let sampleClass = new SampleClass();
回答by Glenn Mohammad
To add to @wprl's answer, the ES6 object method shorthand, like the arrow functions, cannot be used as a constructor either.
添加到@wprl 的答案中,ES6 对象方法简写,如箭头函数,也不能用作构造函数。
const o = {
a: () => {},
b() {},
c: function () {}
};
const { a, b, c } = o;
new a(); // throws "a is not a constructor"
new b(); // throws "b is not a constructor"
new c(); // works