[英]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 === '');
為您的構造函數指定 function 名稱,如下所示:
Namespace.Func = function TheNameOfConstructor (a, b) {
this.a = a;
this.b = b;
};
斷言將像這樣通過:
console.log(f.constructor.name === "TheNameOfConstructor");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.