Home > other >  Is a constructor ever defined on the object itself?
Is a constructor ever defined on the object itself?

Time:04-21

Is there ever a case where the constructor property would be defined on an object/function/class itself, or does it only ever appear on the prototype? For example:

let a = new Array();
console.log(a.hasOwnProperty('constructor'), a.constructor);
// false -- constructor not defined on Array, but Array.prototype

let f = function(){};
console.log(f.hasOwnProperty('constructor'), f.constructor);
// false -- constructor not defined on function, but function.prototype

CodePudding user response:

It would be technically possible for such a thing to occur, but it's a code smell.

function Klass(){
  this.constructor = Klass;
}
const k = new Klass();
console.log(k.hasOwnProperty('constructor'), k);

(You might also see it when someone improperly enter image description here

  • Related