原型链继承
One.prototype.lastName = 'zqc';
function One(){ }
let one = new One();
Two.prototype = one;
function Two(){ }
let two = new Two();
Three.prototype = two;
function Three(){ }
let three = new Three();
打印 three.name 他会找到父级的父级的原型 就是zqc
缺点:他会把想继承的也继承了,没用的继承的也继承了。
构造函数继承
function One(name,age,sex){
this.name = name,
this.age = age,
this.sex = sex
}
function Two(gao,zhong,color){
this.gao = gao,
this.zhong = zhong,
this.color =color
}
function Ren(name,age,sex,gao,zhong,color){
One.call(this,name,age,sex);
Two.call(this,gao,zhong,color)
你继承的只有他构造函数里面的方法,不会继承它原型里面的方法。
}
let ren = new Ren('zqc',21,'man',185,142,'黄皮肤');
缺点:不能继承原型上面的东西。 每次调用都会多调用构造函数。
原型继承
One.prototype.lastName = 'zqc';
function One(){
return this.lastName
}
let one = new One();
Two.prototype = One.prototype;
function Two(){
}
let two = new Two();
two.prototype.name = 'zqc';
缺点:改变One原型的话,影响Two的原型
圣杯模式继承
One.prototype.lastName = 'zqc';
function One(){
return this.lastName
}
// 中间在加一个函数,起到了隔离的作用,今后添加属性时,全部都会加在这个对象里面,所以不会对父级产生影响。
// function inherit(one,two){
// function F(){ };
// F.prototype = one.prototype;
// two.prototype = new F();
// // 修改了constructor的指向,不让他直接指向超级父级
// two.prototype.constructor = two; //指向构造函数
// two.prototype.uber = one.prototype; //指向超级父级
// }
// inherit(One,Two)
// 或 递归的方式,推荐第二种写法。
var inherit = (function(){
var F = function(){};
return function (one,two){
F.prototype = one.prototype;
two.prototype = new F();
two.prototype.constructor = two;
two.prototype.uber = one.prototype;
}
}())
inherit(One,Two)
function Two(){ }
let one = new One();
let two = new Two();
缺点:应该是没有