在 JavaScript 中,通过构造函数实现 继承,也就是通过在子类型 构造函数 中通过 call() 调用父类型构造函数实现继承。
这种方式实现继承继承的优点就是解决了原型链继承中子类实例共享父类引用 属性 的问题,同时,使用该方法还可以实现多继承。
function Object1(attr1, attr2) {
this.attr1 = attr1;
this.attr2 = attr2;
}
function Object2(attr1, attr2, attr3) {
Object1.call(this, attr1, attr2);
this.attr3 = attr3;
}
我们通过在子类型构造函数中通过 call() 调用父类型构造函数,从而实现了继承。
这种方式只是实现部分的继承,如果父类的原型还有方法和属性,子类是拿不到这些方法和属性的。
通过构造函数实现继承
<!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;
}
}
var person = new Person("person", 109);
var student = new Student("haicoder", 109, 100);
console.log("Person =", person);
console.log("Student =", student);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们在 Student 函数中,通过调用 Person.call 实现了 Person 类继承了 Student 类,这种方式只是实现部分的继承,如果父类的原型还有方法和属性,子类是拿不到这些方法和属性的。
在 JavaScript 中,通过构造函数实现继承,也就是通过在子类型构造函数中通过 call() 调用父类型构造函数实现继承。