I just learned that I can overwrite a method in a Javascript class, as shown below, but what about the actual constructor?
If possible, how do I do it 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;
})();
When overriding a constructor: We must call parent constructor as super() in Child constructor before using this .
Having more than one occurrence of a constructor method in a class will throw a SyntaxError error.
A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
Reports a constructor function that returns a primitive value. When called with new , this value will be lost and an object will be returned instead. To avoid warnings, use the @return tag to specify the return of the function.
Just temporarily save the prototype
object, and then replace the constructor function:
var proto = UserModel.prototype;
UserModel = function () { /* new implementation */ };
UserModel.prototype = proto;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With