//clazz.js:
class Clazz { constructor() { this.name = "name"; this.num= 8; } } export default Clazz;
//main.js
import Clazz from "./clazz" let oc = Clazz.prototype.constructor; Clazz.prototype.constructor = function(){ oc.apply(this,arguments) this.num= 9 } let c = new Clazz() console.info(c)
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?
Advertisement
Answer
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
.