JS继承--圣杯模式的详解

继承发展史

  1. 传统的模式 ==> 原型链
Grand.prototype.lastname = "Alex";
function Grand(){
}
 var grand = new grand();
 Father.prototype = Grand;
 function Father(){
	this.name = "Aimee"
}
var father = new Father();
son,prototype = father;
function Son(){

}
var son = new Son();
// 这种传统的继承,过多的继承了没用的属性
  1. 借用构造函数 ==> 利用call 和apply
    按理来说不算标准的继承模式
    缺点:
    不能继承借用构造函数的原型,但是能使用它的功能
    每次构造函数都要多走一个函数 == > 浪费效率
 function person(name,age,sex){
 	this.name = name;
 	this.age = age;
 	this.sex = sex;
 }
 function Alex (name.age,sex,tall){
	person.call(this,name,age,sex);
	this.tall = tall;
}
var alex = new Alex();

  1. 共享原型
    这是一个比较好的继承方法
    但不能随便改动自己的原型
Father.prototype.lastname = "Alex"
	function Father(){
	}
	function son(){
	}
	function inherit(Target,origin){     // 两个参数 一个目标函数每一个是原始函数
		Target.prototype = origin.prototype;
}
	inherit(Son,Father);
	var father = new Father();
	var son = new Son();

既然这种方法不能改动原型,我们就在这种方法的前提上演变出完美的方法

圣杯模式

圣杯模式是在方法三的共有原型,但是在共有原型的基础上有改变。
共享原型是:son.prototype=father.prototype
圣杯模式是:另外加个构造函数 function F(){}当做中间层,然后让 F 和 father 共有一个原型 F.prototype=father.prototype,然后 son.prototype = new F();使用原型链形成了继承关系,现在改 son.prototype 就不会影响 father.prototype

function inherit(Target,origin){
	function F(){};
	F.prototype = origin.prototype;
	Target.prototype = F.prototype;
	Target.prototype.cunstuctor = Target;// 防止constuctor指向紊乱,让Target构造函数指向归位
	Target.prototype.uber origin.prototype;//	找到自己的超级父级,为了让我们知道Target到底继承自谁
}
Father.prototype.lastname = "Alex";
function Father(){
}
function Son(){
}
inherit(Son,Father);
var son = new Son();
var father new Fahter();

有一种高端的写法 YU13 雅虎

var inherit (function(){
var F = function(){};
return  function(Target,Origin){
        F.prototype = Oigin.prototype;
        target.prototype = new F ();
        Target.prototype.constuctor = Target;
        Target.prototype.uber = Origin.prototype;   
    }


})

利用了闭包的机制 ,形成闭包,让F 变成了私有化变量

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值