我们常用下列方式来完成继承
Father.prototype.lastName="Liu";
function Father(){}
function Son(){}
Son.prototype = Father.prototype;
var son = new Son;
var father = new Father;
console.log(son.lastName);//Liu
console.log(father.lastName);//liu
或者将继承用函数表示
Father.prototype.lastName = "Liu";
function Father(){}
function Son(){}
function inherit(Target Origin){
Target.prototype = Origin.prototype;
}
inherit(Son,Father);
var son = new Son();
console.log(Son.lastName)//Liu
但以上方式存在缺点。
我们给son的原型添加属性son.prototype.money:100;
同时构建一个新的对象var father=new Father();
此时如果我们访问father.money
,不难发现father对象里并没有money属性,但结果却是father.money=100
。此时son.prototype.money与father.prototype.money指向同一个。
为避免此种情况,将代码进行完善,从而推出一种完美的模式-----圣杯模式。
function inherit(Target,Origin){
function F(){};
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor =Target;
Target.prototype.uber=Origin.prototype;//查看继承自谁
}
Father.prototype.lastName="Liu";
function Father(){}
function Son(){}
inherit(Son,Father);
var son = new Son();
var father = new Father();
在继承中间添加一个新的对象,来形成原型链。这样一来,解决了上面的问题----更改son的原型但不改变father的属性。
——-在努力,再努力