這是一個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