js的继承方式:
1、原型链继承
function Parent(name){
this.name = name;
this.sayName = function(){
alert(this.name)
}
}
function Child(age){
this.age = age;
this.sayAge = function(){
alert(this.age)
}
}
Child.prototype = new Parent("yang");
var c = new Child();
c.sayName();
优点:写法简单易读。
缺点:无法给父类传参,无法实现多继承
2、call(),apply()继承 ==>(call和apply 继承方式一样,只是传递参数的时候,call是逐个参数传递,而apply是以数组形式传递)
function Parent(name){
this.name = name;
this.sayName = function(){
alert(this.name)
}
}
Parent.prototype.sayHello = function(){
alert("hello");
}
function Child(age){
this.age = age;
this.sayAge = function(){
alert(this.age)
}
}
var c = new Child(18);
Parent.call(c,"yang");
c.sayName();
c.sayHello(); // is not a function
优点:写法简单易读,可以传递参数给父类
缺点:只能继承父类实例的属性和方法,无法继承原型链中的方法
3、混合继承方式(call或apply + 原型链继承)
function Parent(name){
this.name = name;
this.sayName = function(){
alert(this.name)
}
}
Parent.prototype.sayHello = function(){
alert("hello");
}
function Child(age){
this.age = age;
this.sayAge = function(){
alert(this.age)
}
}
Child.prototype = new Parent(); //继承原型链上的方法
var c = new Child(18);
Parent.call(c,"yang"); // 继承父类实例上的属性和方法
c.sayName();
c.sayHello(); // hello
优点:可以实现多继承,可以给父类传递参数,可以继承原型链上面的方法
缺点:两次调用父类实例
4、扩展Object原型继承
Object.prototype.ext = function(obj){
for(var i in obj){
this[i] = obj[i]
}
}
function Person(name){
this.name = name;
this.sayName = function(){
alert(this.name)
}
}
Person.prototype.hello = function(){
alert("hello");
}
function Child(id){
this.id = id;
this.say = function(){
alert(this.name +", "+ this.id)
}
}
var p1 = new Child("1001");
p1.ext(new Person("yang"));
var p2 = new Person("wang");
p1.hello(); // hello
优点:以实现多继承,可以传递参数,可以继承原型链上面的方法