js继承

原型链继承

function SuperType(){
	this.property=true;
}
SuperType.prototype.getSuperValue=function(){
	return this.property;
}
function SubType(){
	this.subproperty=false;
}
SubType.prototype=new SuperType();
SubType.prototype.getSubValue=function(){
	return this.subproperty;
}
var instance=new SubType();
console.log(instance.getSuperValue());//true

问题:

第一:引用类型的原型属性会被所有实例共享

第二:在创建子类型的实例时,不能像超类型的构造函数中传递参数

 

借用构造函数 

function Parent(){
	this.colors=['red','green'];
}
function Child(){
	// 继承
	Parent.call(this);
}
var instance1=new Parent();
instance1.colors.push('blue');
var instance2=new Parent();
console.log(instance2.colors);//["red", "green"]

特点:

第一:可以在子类型构造函数像向超类型构造函数传递参数

第二:函数复用无从谈起

 

 

组合继承

使用原型链实现对原型属性和方法的继承,通过借用构造函数来实现对实例属性的继承

function SuperType(name){
	this.name=name
	this.colors=['red','green'];
}
SuperType.prototype.sayName=function(){
	console.log(this.name);
}
function SubType(name,age){
	SuperType.call(this,name);
	this.age=age;
}
SubType.prototype=new SuperType();
SubType.prototype.constructor=SubType
SubType.prototype.sayAge=function(){
	console.log(this.age);
}
var s1=new SubType('didi',5);
s1.colors.push('blue');
s1.sayAge();
s1.sayName();
console.log(s1.colors);
var s2=new SubType('jiejie',8);
console.log(s2.colors);


原型式继承

function object(o){
	function F(){};
	F.prototype=o;
	return new F();
}
var person={
	name:'xiaoxiao',
	friends:['didi','jiejie']
}
var p1=object(person);
p1.name='yaya';
p1.friends.push('gege');
var p2=object(person);
p2.name='wenwen';
p2.friends.push('meimei');
console.log(person.friends);//["didi", "jiejie", "gege", "meimei"]


寄生式继承

创建一个引用于封装继承过程的函数,该函数在内部以某种方式来增强对象

function object(o){
	function F(){};
	F.prototype=o;
	return new F();
}
function createAnother(original){
	var clone=object(original);
	clone.sayHi=function(){
		console.log('hi');
	}
	return clone;
}
var person={
	name:'xiaoxiao',
	friends:['didi','jiejie']
}
var p1=createAnother(person);
p1.sayHi();//'hi'

寄生组合式继承

通过借用构造函数来继承属性,通过原型链的混成形式来继承方法,思路是:不必为了指定子类型的原型而调用超类型的构造函数,需要的是超类型的一个副本。本质是个就是使用寄生式继承来继承超类型的原型,然后再将结果指定给子类型的原型。

function object(o){
	function F(){};
	F.prototype=o;
	return new F();
}
function inheritPrototype(subType,superType){
	var prototype=object(superType.prototype);
	prototype.constructor=subType;
	subType.prototype=prototype;
}
function SuperType(name){
	this.name=name
	this.colors=['red','green'];
}
SuperType.prototype.sayName=function(){
	console.log(this.name);
}
function SubType(name,age){
	SuperType.call(this,name);
	this.age=age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge=function(){
	console.log(this.age);
}
var p1=new SubType('lili',5);
p1.sayAge();//5
p1.sayName();//'lili'


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值