【问题标题】:Javascript: empty constructor name for instances of "object properties"Javascript:“对象属性”实例的空构造函数名称
【发布时间】:2021-04-19 09:59:31
【问题描述】:

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

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""

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

这里有代码 sn-p:

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 === '');

【问题讨论】:

    标签: javascript constructor namespaces


    【解决方案1】:

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

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

    断言之后会像这样传递:

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

    【讨论】:

    • 有没有办法让构造函数名称为“Namespace.Func”?点似乎不被接受。
    • 我猜函数名中的点是禁止的,所以我建议考虑使用裸函数名,不包括命名空间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2018-02-23
    相关资源
    最近更新 更多