原型链(传统)
过多的继承了没用的属性
Son-->Father-->Grand
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();
借用构造函数
借用构造函数的原型对象实现继承
实现方法的借用
- 不能继承借用构造函数的原型
- 代码累赘,每次调用其构造器都会开辟新的空间来存放这个方法
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
function Student(name,age,sex,grade){
Person.call(this,name,age,sex); //借用Person构造器
this.grade=grade;
}
var student=new Student();
共有原型
Father.prototype
Father Son
Father.prototype.lastName="Deng";
function Father(){
}
function Son(){
}
Son.prototype=Father.prototype; //son和fanther继承自同一个原型
封装:
function inherit(Target,Origin){
Target.prototype=Origin.prototype;
}
// 一定要先继承后用,否则new出的son对象的原型就不是指向Father.prototype,得重写原型。
inherite(Son,Father);
var son=new Son();
缺点:不能实现在不影响其他函数的前提下为某个函数私自添加属性
son.prototype.sex="male";
console.log(son.sex); //male
console.log(father.sex); //male
圣杯模式
弥补共有原型的缺点
Father.prototype
function F(){ }
F.prototype=Father.prototype;
Son.prototype=new F();
Father Son
function inherit(Target,Origin){
function F(){}
F.prototype=Orign.prototype;
Target.prototype=newF();
}
console.log(son.constructor); //function Father(){}
//Son._proto_-->new F()._proto_-->Father.prototype
希望son的constructor是Son
function inherit(Target,Origin){
function F(){}
F.prototype=Orign.prototype;
Target.prototype=newF();
Target.prototype.constructor=Target;
Target.prototype.uber=Origin.prototype; // 希望我们构造出的对象son能够找到自己的超类(超级父级,究竟继承自谁)【超类:super(关键字)改名】
}