Why className.proptotype.constructor = newConstructor() does not change the constructor of Javascript Class?

StackOverflow https://stackoverflow.com/questions/21751524

  •  11-10-2022
  •  | 
  •  

Pergunta

I tried changing the constructor function of a class by

className.proptotype.constructor = newConstrcutor; 

This property now refers to the newConstructor but when i try to create an instance of the class, still the old constructor is executed. So, what exactly is the use of className.proptotype.constructor ?

Thanks

Foi útil?

Solução

Each constructor has a pointer to an object called prototype. The prototype is the main mechanism that JavaScript supports to share properties and methods among objects of the same type.

In addition, the prototype can be used to support inheritance; not exactly in the way that it is done in other OO languages like Java, c# etc. So you can imagine that there is a mechanism that allows the interpreter to navigate from one prototype to another via a chain that is implicitly formed.

In the same way that constructor point to a prototype object, the prototype can also point to its constructor; You can think of it as a relation between constructors and prototypes.

One of the uses of the className.proptotype.constructor property is when you want to debug your code. A JavaScript debugger would clearly state the type (the constructor it was created from) of an instance.

for more details you can read this

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top