昨天看了个视频,跟老师学了一下关于“JS中实现继承的几种方式”的知识,然后写下了笔记,觉得老师讲得很通俗易懂。
function Person(name,age) {
this.name = name;
this.age = age;
this.study = function() {
console.log('正在学习中...');
}
}
Person.prototype.sex = 'female';
Person.prototype.show = function() {
console.log('自我介绍...', this.name + '', this.age + '', this.sex);
}
方式一:对象冒充继承,也称构造继承
核心:使用call,以对象冒充的形式调用父类的构造函数,相当于是复制父类的实例属性给子类
缺点:只能继承父类构造函数中的属性和方法,无法继承原型中的属性和方法
function Student(name,age) {
Person.call(this,name,age); //此时Person中的this指向的是Student的对象
}
var stu1 = new Student('Lucy',15);
console.log(stu1.name, stu1.age); //Lucy,15
stu1.study(); //正在学习中...
//无法继承原型中的属性和方法
console.log(stu1.sex); //undefined
stu1.show; //undefined
方式二:原型链继承
核心:使用prototype,将父类的对象左右子类的原型
缺点:创建子类实例时,无法向父类构造函数传参,导致继承的父类属性没有值
function Student(name,age) {
}
Student.prototype = new Person(); //将Student的原型指向Person实例,从而继承Person
var stu1 = new Student('Lucy',15);
console.log(stu1.name, stu1.age, stu1.sex); //undefined,undefined,female
stu1.study(); //正在学习中...
stu1.show(); //自我介绍... undefined,undefined,female
方式三:组合继承(对象冒充+原型链)
function Student(name,age) {
Person.call(this,name,age);
}
// Student.prototype = new Person(); 调用了两次父类构造函数,生成了两份实例(子类实习将子类原型上的那份屏蔽,所以性能差点)
Student.prototype = Person.prototype; //完美
var stu1 = new Student('Lucy',16);
console.log(stu1.name, stu1.age, stu1.sex); //undefined,undefined,female
stu1.study(); //正在学习中...
stu1.show(); //自我介绍... Lucy,16,female
在此做了下笔记,要是有误的地方请大家多多指点。