继承模式有多少种,各有什么缺点?
1.传统模式,原型链 缺点:过多的继承了没用的属性
<script>
Grandpa.prototype.lastname = "grandpa";
function Grandpa(){
this.name = "grandpa";
}
var grandpa = new Grandpa();
Father.prototype = grandpa;
function Father(){
this.age = 50;
}
var father = new Father();
Son.prototype = father;
function Son(){};
var son = new Son();
</script>
2.借用构造函数,这其实算不上继承,是利用别的函数完成自己的属性建立
缺点:不能继承借用构造函数的原型,每次构造函数都要多走一个函数
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)
this.grade = grade
}
var student = new Student("张三",18,"男","三年级");
console.log(student)
3.共享原型,缺点:不能改动自己的原型
Father.prototype.lastName = "Deng"
function Father(){
}
function Son(){
}
Son.prototype = Father.prototype
var son = new Son();
console.log(son.lastName)
4圣杯模式(new一个新对象中转一下)
function inherit(Target,Origin){
function F(){};
F.prototype = Origin.prototype; //这段代码运行,原型的constuctor会被覆盖
Target.prototype = new F(); //跟着Target的原型里面的constuctor也被覆盖
Target.prototype.constuctor = Target; //还原constuctor
Target.prototype.uber = Origin.prototype; //知道继承谁的
}
Father.prototype.lastName = "Deng";
function Father(){
}
function Son(){
}
inherit(Son,Father);
var father = new Father();
var son = new Son();
console.log(father.lastName);
console.log(son.lastName);

浙公网安备 33010602011771号