我发现这篇关于 javascript 中继承的文章,我认为这是我在网上找到的最好的文章之一,但这篇文章不能用于多重继承,因为它会覆盖过去超类的原型方法和变量
ref : Javascript 继承:调用超级构造函数还是使用原型链?
我想知道是否有办法使用“代理构造函数”的原理进行多重继承(参见堆栈溢出参考帖子)。
我已经尝试过这种方法,我认为它效果很好,但我想了解其他关于限制的意见,如果有的话,关于这个实现。
你需要 jQuery 来运行它或者只使用这个 jsFiddle:http: //jsfiddle.net/NGr2L/
Function.prototype.extend = function(p_parent){
function ctor() {};
//My trick for the Multiple Inheritance is to use the jQuery.extend method
ctor.prototype = $.extend({}, this.prototype, p_parent.prototype);
this.prototype = new ctor();
// I commentd this line of the reference post answer
//because it created multiple constructor which I found confusing
//this.prototype.constructor = this;
}
var Color = (function(){
//Constructor
function Color (p_color){
//Priviligied
this.color = p_color;
//Private
//...
};
//Public
Color.prototype.GetFormattedColor = function(){
return "I'm " + this.color;
};
return Color;
})();
var Animal = (function(){
//Constructor
function Animal (p_name){
//Priviligied
this.name = p_name;
//Private
//...
};
//Public
Animal.prototype.GetFormattedName = function(){
return "my name is " + this.name;
};
return Animal;
})();
var Tiger = (function(){
//Constructor
function Tiger (p_name, p_color, p_kindOfTiger){
//Base constructor
Color.call(this, p_color);
Animal.call(this, p_name);
//Priviligied
this.kindOfTiger = p_kindOfTiger;
//Private
//...
};
//Inheritance
Tiger.extend(Color); //I know, I could've loop
Tiger.extend(Animal);// on the "extend()" arguments to do this in one call
//Public
Tiger.prototype.GetTiger = function(){
return "I'm a " + this.kindOfTiger + ", " +
this.GetFormattedName() + " and " +
this.GetFormattedColor()
};
return Tiger;
})();
var myTiger = new Tiger("Boris", "Aqua", "bengal tiger");
myTiger.GetTiger();
非常感谢