是的,这之前已经被问死了,但是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 告诉我它不是构造函数?
最佳答案
So, why is Node telling me it's not a constructor?
因为它不是构造函数。 :-) 箭头函数从来都不是构造函数,它们关闭 this
并且没有 prototype
属性,因此不能用作构造函数(需要有一个特定的 this
在通过 new
调用时设置,并且需要有一个 prototype
属性,以便它可以用于设置 [[Prototype]] 的通过new
创建的对象)。
要么 1. 将其设为 function
函数,要么 2. 将其设为 class
。
这是 #1 的一行更改:
exports.Config = function(file) {
关于javascript - "Not a constructor",但类型检查出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42938811/