1

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
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

2

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 extends a function class)

Object instances are expected to have a .constructor property on their prototype, not directly on the instance. If property is directly on the instance, that'll cause problems when someone tries to use one of the common methods to iterate over own-properties and finds constructor there.

Another reason why it should be on the prototype and not on the object itself is to take advantage of prototypal inheritance. If a property can exist on one object, on the prototype, better to do that than to duplicate that property everywhere, for every instance. And the constructor property is already automatically on the prototype, so there shouldn't be any need to mess with it anyway.

For similar reasons, class methods are often on the class prototype when possible, rather than duplicated for every single instance. That is, you have all instances inheriting from one prototype with the method, rather than all instances having their own-property method. That is, it's not that good to have

class Klass {
  constructor() {
    this.method = () => console.log('method');
  }
}
const k = new Klass();
k.method();

with the method duplicated for every instance, when you can instead do

class Klass {
  method() {
    console.log('method');
  }
}
const k = new Klass();
k.method();

and have it only on the prototype.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • thanks, could you please clarify what you mean by `For similar reasons, class methods are often on the class prototype when possible`. Do you mean an instance method or a class/static method or something else? Would you want to show a quick code example at the end of your answer to clarify? – David542 Apr 21 '22 at 00:04
0

Look at the doc of Object.prototype.hasOwnProperty.

Unlike the in operator, this method does not check for the specified property in the object's prototype chain.

The constructor property only exists in Object.prototype. And the prototype property only exists in the Object constructor.

enter image description here