Skip to content

Change property value initialized in constructor outside the class


class Clazz {
  constructor() { = "name";
    this.num= 8;
export default Clazz;


import Clazz from "./clazz"
let oc = Clazz.prototype.constructor;
Clazz.prototype.constructor = function(){
    this.num= 9

let c = new Clazz()

While I expect the num of the c will be 9, but it is still 8.

What’s going one? And is it possible to fix that?



Replacing the .constructor property of the prototype object doesn’t help with anything. The constructor is Clazz itself, and you are calling it directly through new Clazz() – it doesn’t create an object and invoke a “constructor method” on it.

Is it possible to fix that?

Not really, no. All you can do is to create a new function (a constructor even) that calls the old one (e.g. by subclassing), and then ensure that you only call the new one with new.

User contributions licensed under: CC BY-SA
6 People found this is helpful