是的,之前已被要求死亡,但none of these为我工作。
调用TypeError: Config is not a constructor
构造函数时,我得到Config
。通过其他SO问题和MDN,看起来这个错误的常见原因是要么遮蔽构造函数,要么调用不可调用的类型,但这些都不会在我的项目中检出。
这是电话:
var Server = require("./server.js").Server;
var Config = require("./config.js").Config;
new Server(new Config("app/config.json")).run();
在./config.js
:
var fs = require("fs");
exports.Config = file => {
var json;
if (fs.existsSync(file) && !fs.lstatSync(file).isDirectory()) {
json = JSON.parse(fs.readFileSync(file));
}
else {
throw new ReferenceError("File doesn't exist: can't load config");
}
this.has = key => {
return json.hasOwnProperty(key);
};
this.get = key => {
return json[key] || null;
};
this.set = (key, value, write) => {
json[key] = value;
if (write) {
fs.writeFileSync(file, JSON.stringify(json));
}
};
};
在调用之前记录Config
的类型会发现它是Function
,所以几乎可以肯定它与config.js
中定义的功能相同。那么,为什么Node告诉我它不是构造函数?
答案 0 :(得分:4)
那么,为什么Node告诉我它不是构造函数?
因为它不是构造函数。 :-)箭头函数永远不是构造函数,它们靠近this
并且没有prototype
属性,因此不能用作构造函数(当它们需要设置特定的this
时通过new
调用,需要有一个prototype
属性,以便它可用于设置通过new
创建的对象的[[Prototype]]。
1.将其设为function
功能,或2.将其设为class
。
以下是#1的一行更改:
exports.Config = function(file) {