我想命名我的代码,所以我这样做了:
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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句