[英]Javascript: empty constructor name for instances of “object properties”
I want to namespace my code, so I did this:我想命名我的代码,所以我这样做了:
let Namespace = {};
Namespace.Func = function (a, b) {
this.a = a;
this.b = b;
};
Namespace.Func.prototype.getSum = function () {
return this.a + this.b;
};
Then, I created an instance of Namespace.Func
:然后,我创建了Namespace.Func
的一个实例:
let f = new Namespace.Func(1, 2);
Now, I would expect all these lines to be true:现在,我希望所有这些行都是真的:
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");
But the last one is false
, because f.constructor.name
is ""
.但最后一个是false
,因为f.constructor.name
是""
。
Why is that?这是为什么? Can it be fixed?可以修复吗?
Here you have the code snippet:这里有代码片段:
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 === '');
Specify function name for your constructor like below:为您的构造函数指定 function 名称,如下所示:
Namespace.Func = function TheNameOfConstructor (a, b) {
this.a = a;
this.b = b;
};
The assert will pass after that like this:断言将像这样通过:
console.log(f.constructor.name === "TheNameOfConstructor");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.