“不是构造函数”,但types检查
是的,这已被要求死亡,但这些 都没有为我工作。
我得到一个TypeError: Config is not a constructor
当调用Config
构造TypeError: Config is not a constructor
时, Config
TypeError: Config is not a constructor
函数。 通过其他SO问题和MDN ,看来这个错误的常见原因是阴影构造函数或调用一个不可调用的types,但这两个都没有在我的项目中检查。
这是电话:
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)); } }; };
在调用之前loggingConfig
的types显示它是一个Function
,所以它几乎可以肯定是在config.js
定义的相同的函数。 那么,为什么Node告诉我这不是一个构造函数呢?
那么,为什么Node告诉我这不是一个构造函数呢?
因为它不是一个构造函数。 :-)箭头函数从来都不是构造函数,它们closures了this
,没有prototype
属性,所以不能用作构造函数(当它们通过new
被调用时需要有一个特定的集合,并且需要一个prototype
属性所以它可以用来设置通过new
创build的对象的[[Prototype]]。
要么1.使之成为一个function
函数,2.要使它成为一个class
。
以下是#1的一行更改:
exports.Config = function(file) {