Javascript:"object properties" 实例的空构造函数名称

Javascript: empty constructor name for instances of "object properties"

我想为我的代码命名空间,所以我这样做了:

let Namespace = {};

Namespace.Func = function (a, b) {
  this.a = a;
  this.b = b;
};
Namespace.Func.prototype.getSum = function () {
  return this.a + this.b;
};

然后,我创建了一个 Namespace.Func:

的实例
let f = new Namespace.Func(1, 2);

现在,我希望所有这些行都是正确的:

console.log(f.getSum() === 3);
console.log(typeof f === 'object');
console.log(f instanceof Object);
console.log(f instanceof Namespace.Func);
console.log(f.constructor === Namespace.Func);
console.log(f.constructor.name === "Namespace.Func");

但是最后一个是false,因为f.constructor.name"".

这是为什么?可以修复吗?

这里有代码片段:

let Namespace = {};

Namespace.Func = function (a, b) {
  this.a = a;
  this.b = b;
};
Namespace.Func.prototype.getSum = function () {
  return this.a + this.b;
};

let f = new Namespace.Func(1, 2);

console.log("f.getSum() === 3", f.getSum() === 3);
console.log("typeof f === 'object'", typeof f === 'object');
console.log("f instanceof Object", f instanceof Object);
console.log("f instanceof Namespace.Func", f instanceof Namespace.Func);
console.log("f.constructor === Namespace.Func", f.constructor === Namespace.Func);
console.log("f.constructor.name === 'Namespace.Func'", f.constructor.name === 'Namespace.Func');
console.log('---');
console.log("f.constructor.name", f.constructor.name);
console.log("f.constructor.name === ''", f.constructor.name === '');

为您的构造函数指定函数名称,如下所示:

Namespace.Func = function TheNameOfConstructor (a, b) {
  this.a = a;
  this.b = b;
};

之后断言会像这样通过:

console.log(f.constructor.name === "TheNameOfConstructor");