Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to clone JavaScript class

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

function MyClass() {
}

MyClass.prototype = {
};

Now I want to create a copy of that class (not a copy of the instance the class creates) but change some of the prototype methods. In other words I want to make a copy of the class with some augmentations... do I need to use inheritance for that or I it is enough to loop over and assign references to my new class for the original prototype and the new one?

like image 930
Pass Avatar asked Mar 28 '11 12:03

Pass


1 Answers

I would use normal inheritance. Try this:

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
like image 63
Neall Avatar answered Sep 18 '22 23:09

Neall