本文通过具体代码示例,演示如何在JavaScript中利用构造函数实现继承。核心步骤包括定义父类Person和子类Student,并通过call方法在子类构造函数中调用父类构造函数,从而将父类属性复制到子类实例中,实现属性复用。
JavaScript构造函数继承示例:利用call方法实现子类属性复用
代码如下:
首先创建父类
function Person(name, age, address) {
this.name = name;
this.age = age;
this.address = address;
}
// 创建子类
function Student(score) {
this.score = score;
// 可以使用 call 方法或 apply 方法来调用父类的构造函数
// 通过 call 方法调用父类 Person 的构造函数,这会在 Student 实例中初始化 Person 对象的属性副本,使 Student 拥有这些属性
Person.call(this, "zhangsan", 22, "中国北京!");
}
var student = new Student(100);
alert(student.address + student.score + "分"); // 上述 Person.call 方法调用中,第二个参数开始为传递的数据参数