突然发现自己好久没有更新博客,今天刚好研究js的继承,感觉挺有意思的,特拿来给大家分享一下。
第一阶段 通过原型和原型链实现继承
<script type="text/javascript">
Grand.prototype.lastName = 'lin';
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();
console.log(son.lastName);
</script>
打印结果
这种方式的缺点是,后代不想继承某些属性,也会被链式的继承来。降低了开发效率。
第二阶段 借用构造函数的call/apply方法
1.使用call方法
<script type="text/javascript">
function Person(name,age){
this.name = name;
this.age = age;
}
function Student(name,age,sex,score){
Person.call(this,name,age);
this.sex = sex;
this.score = score;
}
var student = new Student('zhangsan',34,'male',98);
console.log(student);
</script>
2.使用apply方法
<script type="text/javascript">
function Person(name,age){
this.name = name;
this.age = age;
}
function Student(name,age,sex,score){
// 与call的区别是这里是数组实现的。
Person.apply(this,[name,age]);
this.sex = sex;
this.score = score;
}
var student = new Student('zhangsan',34,'male',98);
console.log(student);
</script>
打印结果
缺点:1.不能继承借用构造函数的原型 2.每次构造函数都要多执行一个函数,降低开发效率。
第三阶段 共享原型
<script type="text/javascript">
Person.prototype.hobby = "yin";
function Person(){
}
function Student(){
}
function inherit(Target,Origin){
Target.prototype = Origin.prototype;
}
inherit(Student,Person);
var person = new Person();
var student = new Student();
Student.prototype.name = 'zhangsan';
console.log(student.hobby);
console.log(student.constructor);
console.log(Person.prototype);
</script>
打印如下:
缺点:1.子代修改了原型的属性,将导致父代原型的修改;2.后代的constructor函数不再指向自己。
第四阶段 圣杯模式
<script type="text/javascript">
Person.prototype.hobby = "yin";
function Person(){
}
function Student(){
}
//定义一个实现继承的函数
function inherit(Target,Origin){
function F(){};
F.prototype = Origin.prototype;
Target.prototype = new F();
}
// 调用继承函数
inherit(Student,Person);
var person = new Person();
var student = new Student();
Student.prototype.name = 'zhangsan';
console.log(student.hobby);
console.log(student.constructor)
console.log(Person.prototype);
</script>
打印如下:
从打印结果来看此模式改善了共享原型的第一个缺点,但是第二个缺点没有完善。下面拿出杀手锏进行完善圣杯模式
<script type="text/javascript">
Person.prototype.hobby = "yin";
function Person(){
}
function Student(){
}
//定义一个实现继承的函数
// function inherit(Target,Origin){
// function F(){};
// F.prototype = Origin.prototype;
// Target.prototype = new F();
// }
// 利用闭包的私有属性改造函数让student.constructor指向自己
var inherit = (function(){
var F = function(){};
return function(Target,Origin){
F.prototype = Origin.prototype;
Target.prototype = new F();
// 重点来了
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}());
// 调用继承函数
inherit(Student,Person);
var person = new Person();
var student = new Student();
Student.prototype.name = 'zhangsan';
console.log(student.hobby);
console.log(student.constructor)
console.log(Person.prototype);
</script>
打印结果
完美实现,太开心了。