js语法非常灵活,不仅可以用原型继承,还有其他办法。如:原型冒充或复制继承。
1.原型冒充
function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
};
}
function Cat(name){
Animal.apply(this,arguments);
}
var cat = new Cat('cat');
cat.showName();
其中Animal的所有属性和方法都应用到了Cat上,cat中存在所有Animal的所有属性和方法。
2.复制继承
function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
};
}
function Cat(name){
this.extend = function(parent){
for(var key in parent){
this[key] = parent[key];
}
}
}
var animal = new Animal('animal');
var cat = new Cat('cat');
cat.extend(animal);
console.log(cat);