Extending, instead of overwriting, the prototype

In our current code base, we create classes like this

my_class = function(){ //do some constructor stuff } my_class.prototype = { var1 : 'value', var2 : 'value', var3 : 'value' . . . //etc } 

There are several classes that I would like to inherit a superclass from. However, if I do something like this, I will eventually rewrite the prototype of the superclass.

 my_super_class = function(){ } my_super_class.prototype.generic_function = function(){ //all subclasses should have this function } my_subclass = function(){ //constructory stuff } //inherit the superclass my_class.prototype = new my_super_class(); my_class.prototype = { //oops, there goes my superclass prototype... var1 : 'value', var2 : 'value', var3 : 'value' . . . //etc } 

Is there a better way to do this than my_class.prototype.val1 = 'value'; ... etc. after superclass inheritance? I would like to stick to the convention from our current code base, because it is short and corresponds to a point.

+4
source share
4 answers

Do you use any library or framework? If you do this, then chances are you can use something like Prototype Object.extend or jQuery.extend.

What may also seem interesting to you is the new Object.create from ECMA-262 5th Edition .

+3
source

What you can do is write a merge function:

 function merge(one, other) { for(var k in other) { if(other.hasOwnProperty(k) && !one.hasOwnProperty(k)) { one[k] = other[k]; } } } 

Then you will do it with prototype :

 merge(my_class.prototype, { var1 : 'value', var2 : 'value', var3 : 'value' . . . //etc }); 
+3
source

You can write a function that processes you property assignment:

 function extend(a, b) { for(var prop in b) { if(b.hasOwnProperty(prop)) { a[prop] = b[prop]; } } } my_class.prototype = new my_super_class(); var my_class_proto = { //... } extend(my_class.prototype, my_class_proto); 
+2
source

I am also trying to find good syntax for these things in JavaScript, but I saw something like this:

 // inherit the superclass myClass.prototype = new mySuperClass(); (function() { this.var1 = 'value'; this.var2 = 'value'; // etc. }).call(myClass.prototype); 

Which seems nicer than writing myClass.prototype all the time.

0
source

Source: https://habr.com/ru/post/1341063/


All Articles