JS中的继承,重点:圣杯模式

1.原型链的继承

Grand.prototype.lastName = ‘Ji’;

function Grand(){
}

var grand = new Grand();

Father.prototype = grand;

function Father(){

this.name=’hehe’;
}

var father = new Father();

Son.prototype = father;

function Son(){
}

var son = new Son();

扫描二维码关注公众号,回复: 5030543 查看本文章

缺点:不仅继承了Grand的lastName,而且继承了Father的name;

2.借用构造函数:
call和apply

不能继承借用构造函数的原型,每次构造函数都要多走一个函数

3.共享原型

Father.prototype.lastName = ‘Deng’;

function Father(){
}

function Son(){
}

function inherit(Target ,Origin){

Target.prototype = Orgin.prototype;
}

inherit(Son,Father);

//extend inherit继承font-size : inherit(自动继承父亲的font-size(默认值))

不能随便改动自己的原型(改变一个父子都会改变)

4.圣杯模式

function inherit(Targer, Origin){

function F(){};
F.prototype = Origin.prototype;

Target.prototype = new F();

Target.prototype.constuctor = Target;

Target.prototype.uber = Origin.prototype;
}

//son.__proto__ -->new F().__proto__ -->Father.prototype

var inherit = (function(){

var F = function(){};    //闭包,变成私有化变量,在函数外部无法调用

return function(Targer, Origin)

{

F.prototype = Origin.prototype;

Target.prototype = new F();

Target.prototype.constuctor = Target;

Target.prototype.uber = Origin.prototype;
}

}());

猜你喜欢

转载自blog.csdn.net/duyujian706709149/article/details/83997567