//原型继承
Father.prototype.lastName="Deng";
function Father(){
}
function Son(){
}
function inherit(Target,Origin){
Target.prototype=Origin.prototype;
}
//var son=new Son();如果写在继承之前不会继承father原型的值
inherit(Son,Father);
var son=new Son();
//不足
//给son原型添加属性,father也会被更改
Son.prototype.sex="F";
inherit(Son,Father);
var son=new Son();
var father=new Father();
console.log(father.sex);//F
//改变
//圣杯模式
function inherit(Target,Origin){
function F(){};
F.prototype=Father.prototype;//让F的原型指向Father的原型
Son.prototype=new F();//让Son的原型(相当于F的实例对象会继承F函数的属性)也继承F原型,
//但是这样更改了son的构造函数
//son.constructor=Father
Target.prototype.constructor=Target;
}
Father.prototype.lastName="Deng";
function Father(){
}
function Son(){
}
inherit(Son,Father);
var son=new Son();
var father=new Father();
继承模式 圣杯模式
最新推荐文章于 2020-06-24 21:54:32 发布