“不是构造函数”,但类型检查

时间:2017-03-21 21:52:34

标签: javascript node.js constructor

是的,之前已被要求死亡,但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告诉我它不是构造函数?

1 个答案:

答案 0 :(得分:4)

  

那么,为什么Node告诉我它不是构造函数?

因为它不是构造函数。 :-)箭头函数永远不是构造函数,它们靠近this并且没有prototype属性,因此不能用作构造函数(当它们需要设置特定的this时通过new调用,需要有一个prototype属性,以便它可用于设置通过new创建的对象的[[Prototype]]。

1.将其设为function功能,或2.将其设为class

以下是#1的一行更改:

exports.Config = function(file) {