Best way to clone a JavaScript class

I have a class declared in the traditional way, i.e.

function MyClass() { } MyClass.prototype = { }; 

Now I want to create a copy of this class (and not a copy of the instance created by the class), but change some prototype methods. In other words, I want to make a copy of the class with some additions ... do I need to use inheritance for this, or am I enough to iterate and assign references to my new class for the original prototype and the new?

+4
source share
3 answers

I would use regular inheritance. Try the following:

 var MyClass = function(){}; MyClass.prototype = { foo: function(){ alert('foo') }, bar: function(){ alert('bar') } }; var MySubClass = function(){}; MySubClass.prototype = new MyClass(); MySubClass.prototype.bar = function(){ alert('otherbar') }; var my = new MyClass(); var mysub = new MySubClass(); my.foo(); // foo my.bar(); // bar mysub.foo(); // foo mysub.bar(); // otherbar 
+9
source

Combination inheritance (sometimes also called pseudo-classical inheritance) combines a prototype chain and a design theft to get the most out of every approach.

 function SuperType(name){ this.name = name; this.colors = ['red', 'blue', 'green']; } SuperType.prototype.sayName = function(){ alert(this.name); }; function SubType(name, age){ //inherit properties SuperType.call(this, name); this.age = age; } //inherit methods SubType.prototype = new SuperType(); 
+4
source

It’s illogical to just clone your class, the average general characteristic of a class, if you want to just clone a class its Event is not logical, but simply cloning, which you must use to use its object. You must use inheritance to subclass an existing class. read the full article on inheritance in

https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited

+1
source

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


All Articles