简体   繁体   English

克隆JavaScript类的最佳方法

[英]Best way to clone JavaScript class

I have a class declared the traditional way, ie 我有一个阶级宣称传统的方式,即

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? 换句话说,我想用一些扩充来制作一个类的副本......我是否需要使用继承呢?或者它足以循环并为原始原型和新原型分配对我的新类的引用?

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. 这对于克隆你的类来说是不合逻辑的,类是指共享的charactaristics,如果你想克隆它的事件而不是逻辑而不仅仅是克隆,你应该使用它来对其对象进行插入。 You should use inheritance to create sub classes of the existing class. 您应该使用继承来创建现有类的子类。 read full article about inhertiance at 阅读关于inhertiance的全文

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM