简体   繁体   中英

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 :

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM