Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overwrite a constructor in javascript?

Tags:

javascript

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;
})();
like image 641
Industrial Avatar asked Nov 14 '12 21:11

Industrial


People also ask

Can you override a constructor JavaScript?

When overriding a constructor: We must call parent constructor as super() in Child constructor before using this .

What happens if you write constructor more than once in a class in JavaScript?

Having more than one occurrence of a constructor method in a class will throw a SyntaxError error.

How does a constructor work in JavaScript?

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.

Can a JavaScript constructor return a primitive value?

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.


1 Answers

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

var proto = UserModel.prototype;
UserModel = function () { /* new implementation */ };
UserModel.prototype = proto;
like image 148
Šime Vidas Avatar answered Oct 29 '22 05:10

Šime Vidas