这是一个elclanrs解决方案的延伸(原谅双关语)包括实例方法的细节,并对问题的这个方面采取可扩展的方法;我完全承认,由于David Flanagan的“JavaScript:权威指南”(部分调整了此背景),这一切都归结在一起。请注意,这显然比其他解决方案更详细,但可能会从长远角度来看。
首先,我们使用大卫的简单的“扩展”功能,副本属性指定的对象:
function extend(o,p) {
for (var prop in p) {
o[prop] = p[prop];
}
return o;
}
然后我们实现自己的子类定义工具:
function defineSubclass(superclass, // Constructor of our superclass
constructor, // Constructor of our new subclass
methods, // Instance methods
statics) { // Class properties
// Set up the prototype object of the subclass
constructor.prototype = Object.create(superclass.prototype);
constructor.prototype.constructor = constructor;
if (methods) extend(constructor.prototype, methods);
if (statics) extend(constructor, statics);
return constructor;
}
对于准备的最后一位我们用David的新jiggery-pokery增强了我们的功能原型:
Function.prototype.extend = function(constructor, methods, statics) {
return defineSubclass(this, constructor, methods, statics);
};
定义我们的怪物下课后,我们就以下(这是可以重复使用的,我们希望扩展/继承任何新类):
var Monkey = Monster.extend(
// constructor
function Monkey() {
this.bananaCount = 5;
Monster.apply(this, arguments); // Superclass()
},
// methods added to prototype
eatBanana: function() {
this.bananaCount--;
this.health++;
this.growl();
}
);
的[?如何从在JavaScript类继承]可能的复制(http://stackoverflow.com/问题/ 2107556 /如何在javascript中继承类) – 2016-11-20 12:42:26