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 augm开发者_如何学编程entations... 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?
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
Combination inheritance (sometimes also called pseudoclassical inheritance) combines prototype chaining and constructor stealing to get the best of each 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();
This is not logical to just clone your class, class mean shared charactaristics, if you want to just clone the class its event not logical instead of just cloning you should use to intainsiate its object. You should use inheritance to create sub classes of the existing class. read full article about inhertiance at
https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited
精彩评论