js学习记录(1)——构造函数和继承的几种实现

构造函数和继承的几种实现

构造函数

1.组合使用构造函数模式和原型模式
组合使用构造函数模式和原型模式即在构造函数中定义实例属性,在原型中定义方法和共享的属性。

function Person(name,age)
{
	this.name=name;
	this.age=age;
	this.friends=["shelby","Court"];
}
Person.prototype={
	constructor:Person,
	sayName:function(){
		console.log(this.name)
	}
}
var instance=new Person("Niko",45);
instance.sayName();

2.动态原型模式
动态原型模式将原型初始化放到了构造函数中,看上去更整体了些。同时对原型是否已经初始化进行了判断,避免了重复初始化。

function Person(name,age)
{
	this.name=name;
	this.age=age;
	this.friends=["shelby","Court"];
	if(typeof this.sayName!="function"){   
		Person.prototype.sayName=function(){
			console.log(this.name);
		}
	}
}
var instance=new Person("Niko",45);
instance.sayName();

继承

1.组合继承
组合继承即使用原型链实现对原型属性和方法的继承,用借用构造函数实现对实例属性的继承。

function SuperType(name){
	this.name=name;
	this.colors=["red","blue","green"];
}
SuperType.prototype.sayName=function(){
	console.log(this.name);
}
function SubType(name,age){
	SuperType.call(this,name);    //借用构造函数
	this.age=age;
}
SubType.prototype=new SuperType("super");  //原型链
var instance=new SubType("Niko",43);
instance.sayName();

2.寄生组合式继承
寄生组合式继承是通过借用构造函数继承属性,通过原型链的混成形式继承方法。

function object(o){
	function F(){}
	F.prototype=o;
	return new F();
}
function inheritPrototype(subType,superType){
	var p=object(superType.prototype);
	p.constructor=subType;
	subType.prototype=p;
}
function SuperType(name){
	this.name=name;
	this.colors=["red","blue","green"];
}
SuperType.prototype.sayName=function(){
	console.log(this.name);
}
function SubType(name,age){
	SuperType.call(this,name);    
	this.age=age;
}
inheritPrototype(SubType,SuperType);
var instance=new SubType("Niko",43);
instance.sayName();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值