javascript - "Not a constructor",但类型检查出来

标签 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 告诉我它不是构造函数?

最佳答案

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/

相关文章:

javascript - Rails、javascript 和更新表单

javascript - 如何在 JavaScript 匿名函数的声明时使用变量的值?

node.js - 如何保持用户登录? ExpressJS 和 Passport 有可能吗?

c++ - 构造函数不抛出异常

javascript - 如何按名称将 Google map 置于国家/地区的中心

javascript - 动态访问json数组元素的方法

node.js - Dockerfile build/bin/sh -c 返回非零代码 : 1

node.js - 在mongodb中查询字符串日期格式

C++ 构造函数不会传递字符串 - 未定义构造函数

c++ - cpp 没有匹配的函数调用来调用构造函数。为什么?