在 JavaScript 中,通过组合实现 继承,也就是通过调用父类 构造函数,继承父类的 属性 并保留传参的优点,然后通过将父类实例作为子类 原型,实现 函数 复用。
这种方式融合 原型链继承 和 构造函数 的优点,是 JavaScript 中最常用的继承模式。不过也存在缺点就是无论在什么情况下,都会调用两次构造函数。
function Object1(attr1, attr2) {
this.attr1 = attr1;
this.attr2 = attr2;
}
function Object2(attr1, attr2, attr3) {
Object1.call(this,attr1,attr2);
this.attr3 = attr3;
}
Object2.prototype = new Object1();
Object2.prototype.constructor = Object2; //组合继承也是需要修复构造函数指向的
通过原型链和构造函数的组合实现了继承。
这种方式的缺点就是无论在什么情况下,都会调用两次构造函数:一次是在创建子类型原型的时候,另一次是在子类型构造函数的内部,子类型最终会包含父类型对象的全部实例属性,但我们不得不在调用子类构造函数时重写这些属性。
通过组合实现继承
<!DOCTYPE html>
<html>
<head>
<title>JavaScript组合实现继承</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function Person(name, age) {
this.name = name;
this.age = age;
this.setName = function(name){
this.name = name;
}
}
Person.prototype.setAge = function (age) {
this.age = age;
}
function Student(name, age, score){
Person.call(this, name, age);
this.score = score;
this.setScore = function (score) {
this.score = score;
}
}
Student.prototype = new Person();
Student.prototype.constructor = Student; //组合继承也是需要修复构造函数指向的
var p1 = new Person('HaiCoder', 21);
var s1 = new Student('Tom', 20, 15000);
console.log("Person =", p1);
console.log("Student =", s1);
console.log("Person constructor =", p1.constructor);
console.log("Student constructor =", s1.constructor);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们通过组合原型链继承和构造函数继承的方式,实现了继承。
在 JavaScript 中,通过组合实现继承,也就是通过调用父类构造函数,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用。