JS继承模式

JS继承模式

继承发展史

1 传统模式 -->原型链

 过多继承了没用属性

Grand.prototype.lastNmae= 'Wang';
function Grand() {

}
var grand = new Grand();

Father.prototype = grand;
function  Father() {

}
var father  =  new Father();

Son.prototype = father;
function  Son() {

}

2 借用构造函数

不能继承借用构造函数的原型

每次构造函数都要多走一个函数

function Person(name,age,sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}
function Stuendt(name,age,sex,grade) {
    Person.call(this,name,age,sex);
    this.grade = grade;
}
var student = new Stuendt("j",23,'male',2017);

3共享原型

不能随便改动自己的原型

Father.prototype.lastName = 'Wang';
function Father() {

}
function Son()  {

}
Son.prototype = Father.prototype;
var son = new Son();
var father  = new Father();

优化以上代码

Father.prototype.lastName = 'Wang';
function Father() {

}
function Son()  {

}

function inherit(Target,Origin) {
    Target.prototype = Origin.prototype;

}
inherit(Son,Father);
var son = new Son();
var father  = new Father();

但是这里如果son 要加一个属性则会影响father

eg:

Father.prototype.lastName = 'Wang';
function Father() {

}
function Son()  {

}

function inherit(Target,Origin) {
    Target.prototype = Origin.prototype;

}
inherit(Son,Father);
Son.prototype.sex = "male";
var son = new Son();
var father  = new Father();

很明显改动son后father的原型也发生了改变。

4圣杯模式

Father.prototype.lastName = 'Wang';
function Father() {

}
function Son()  {

}

function inherit(Target,Origin) {
    function F(){}
    F.prototype = Origin.prototype;
    Target.prototype = new F();

}
inherit(Son,Father);
Son.prototype.sex = "male";
var son = new Son();
var father  = new Father();

但是这里还存在一个问题:

 

son._proto_    -->   new F()._proto_   -->    Father.proto

所以为了让 son的constructor变为自己的,所以继续优化得:
 

Father.prototype.lastName = 'Wang';
function Father() {

}
function Son()  {

}

function inherit(Target,Origin) {
    function F(){}
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constructor =  Target;

}
inherit(Son,Father);
Son.prototype.sex = "male";
var son = new Son();
var father  = new Father();

这就是为了让son 的构造函数变为自己的

Target.prototype.constructor =  Target;

这里为了能够让son知道 自己继承自谁所以以上程序可以继续优化得:

Father.prototype.lastName = 'Wang';
function Father() {

}
function Son()  {

}

function inherit(Target,Origin) {
    function F(){}
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constructor =  Target;
    Target.prototype.uber = Origin.prototype;
}
inherit(Son,Father);
Son.prototype.sex = "male";
var son = new Son();
var father  = new Father();

这里增加了

Target.prototype.uber = Origin.prototype;

这就是圣杯模式。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值