JS的几种继承方式

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

优点:以实现多继承,可以传递参数,可以继承原型链上面的方法

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值