继承
通俗来说,就是子类能够继承父类构造函数及原型对象上的属性和方法。那么怎么实现继承呢?
1. 原型继承
实现原理:因为实例对象上有构造函数和他的原型对象上的所有属性和方法,被所有实例共享
代码实现:
父类为 Person,子类为Student
function Person() {
this.name = '小明';
this.has = ['车', '房'];
}
Person.prototype.getName = function () {
console.log("我的名字是:" + this.name);
}
function Student() {
this.major = "English";
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
// 以下测试代码
var student1 = new Student();
student1.has.push("存款"); //s99行
console.log(student1)
原型继承带来的问题:
- 不能传参给父类
- 父类属性是引用类型, 会被子类篡改
这里 s99 行给子类 Student 的 has 属性增加了一个“存款”,父类Person的has属性也改了。
2. 构造函数继承
实现原理:在子类构造函数中直接调用父类构造函数
代码实现:
父类为 Person,子类为Student,以下几种实现方法同上。
function Person(args) {
this.name = '小明';
this.has = ['车', '房'];
}
Person.prototype.getName = function () {
console.log("我的名字是:" + this.name);
}
function Student(args) {
Person.call(this,args) //调用父类构造函数,并修改this指向为Student
this.major = "English"; //这里涉及原型链继承会先找自己身上有没有该属性,找不到再沿着原型链向上找。所以子类自己属性放在上一行代码的下面。如果有同名属性,覆盖上级
}
// 以下测试代码
var student1 = new Student('学生1');
student1.has.push("存款");
console.log(student1)
构造函数继承解决了原型继承的问题,但也有不足:
- 不能继承父类原型对象 prototype 上的方法
3. 组合式继承
实现原理:将以上两种方法组合起来使用
代码实现:
function Person(args) {
this.name = '小明';
this.has = ['车', '房'];
}
Person.prototype.getName = function () {
console.log("我的名字是:" + this.name);
}
function Student(args) {
Person.call(this,args)
this.major = "English";
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
// 以下测试代码
var student1 = new Student('学生1');
student1.has.push("存款");
console.log(student1)
问题:父类构造函数被执行了两次
3. 寄生组合式继承
实现原理:在组合式继承的基础上,使用Object.create创建空对象,并实现继承。
A = Object.create( B ) 会创建一个新对象,并使 A 的原型,指向 B
A.__proto__ === B
代码实现:
function Person(args) {
this.name = '小明';
this.has = ['车', '房'];
}
Person.prototype.getName = function () {
console.log("我的名字是:" + this.name);
}
function Student(args) {
Person.call(this,args)
this.major = "English";
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
// 以下测试代码
var student1 = new Student('学生1');
student1.has.push("存款");
console.log(student1)