Is it possible to rewrite the constructor in javascript?

I just found out that I can overwrite a method in a Javascript class as shown below, but what about the actual constructor?

If possible, how to do this without instantiating the class?

var UserModel = (function() { var User; User = function() {}; // <- I want to overwrite this whilst keeping below methods User.prototype.isValid = function() {}; return User; })(); 
+6
source share
2 answers

Just temporarily save the prototype object, and then replace the constructor function:

 var proto = UserModel.prototype; UserModel = function () { /* new implementation */ }; UserModel.prototype = proto; 
+9
source

Basically, you create a temporary function that does nothing, you install your prototype, has a prototype of the parent class, then you can use the base class as the parent without calling its constructor.

If you need to reference the constructor of the parent class from the constructor of the child class, you must use Function.prototype.apply to redirect the constructor call.

Javascript inheritance model:

 // Base class var Base = function ( ) { this.foo = 40; }; Base.prototype.bar = function ( ) { return this.foo; }; // Inherited class var Child = function ( ) { Base.apply( this, arguments ); this.foo += 2; }; var F = function ( ) { }; F.prototype = Base.prototype; Child.prototype = new F( ); 
0
source

All Articles