继承发展史
- 传统的模式 ==> 原型链
Grand.prototype.lastname = "Alex";
function Grand(){
}
var grand = new grand();
Father.prototype = Grand;
function Father(){
this.name = "Aimee"
}
var father = new Father();
son,prototype = father;
function Son(){
}
var son = new Son();
// 这种传统的继承,过多的继承了没用的属性
- 借用构造函数 ==> 利用call 和apply
按理来说不算标准的继承模式
缺点:
不能继承借用构造函数的原型,但是能使用它的功能
每次构造函数都要多走一个函数 == > 浪费效率
function person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
function Alex (name.age,sex,tall){
person.call(this,name,age,sex);
this.tall = tall;
}
var alex = new Alex();
- 共享原型
这是一个比较好的继承方法
但不能随便改动自己的原型
Father.prototype.lastname = "Alex"
function Father(){
}
function son(){
}
function inherit(Target,origin){ // 两个参数 一个目标函数每一个是原始函数
Target.prototype = origin.prototype;
}
inherit(Son,Father);
var father = new Father();
var son = new Son();
既然这种方法不能改动原型,我们就在这种方法的前提上演变出完美的方法
圣杯模式
圣杯模式是在方法三的共有原型,但是在共有原型的基础上有改变。
共享原型是:son.prototype=father.prototype
圣杯模式是:另外加个构造函数 function F(){}当做中间层,然后让 F 和 father 共有一个原型 F.prototype=father.prototype,然后 son.prototype = new F();使用原型链形成了继承关系,现在改 son.prototype 就不会影响 father.prototype
function inherit(Target,origin){
function F(){};
F.prototype = origin.prototype;
Target.prototype = F.prototype;
Target.prototype.cunstuctor = Target;// 防止constuctor指向紊乱,让Target构造函数指向归位
Target.prototype.uber origin.prototype;// 找到自己的超级父级,为了让我们知道Target到底继承自谁
}
Father.prototype.lastname = "Alex";
function Father(){
}
function Son(){
}
inherit(Son,Father);
var son = new Son();
var father new Fahter();
有一种高端的写法 YU13 雅虎
var inherit (function(){
var F = function(){};
return function(Target,Origin){
F.prototype = Oigin.prototype;
target.prototype = new F ();
Target.prototype.constuctor = Target;
Target.prototype.uber = Origin.prototype;
}
})
利用了闭包的机制 ,形成闭包,让F 变成了私有化变量