JS中原型继承
0、前言
尽管ES6标准已经提供类继承机制,但在之前被广泛使用的原型继承机制对理解JS的原型有很大的帮助,所以这里练习梳理一下,开始之前,先熟悉三个概念:构造函数、对象、原型以及它们之间的关系,可以我的另一篇文章:JS中构造函数,实例,原型的关系
1、思路
对JS的原型链理解之后,不难得出下面的代码思路:
-
编写父类构造函数
Super
和原型方法。(构造函数内定义属性,原型上定义方法) -
创建子类构造函数
Derived
。-
使用父类构造函数的
Super.call(this,args)
-
子类的属性定义
-
-
修正原型链:
Derived.prototype = Object.create(Super.prototype)
-
定义子类的原型方法
2、代码示例
//父类构造函数
function Person(name,age){
this.name=name;
this.age=age;
}
// 父类方法
Person.prototype.sayHello=function(){
console.log("Hello!");
};
// 子类构造函数
function Student(name,age,grade){
// 继承父类的属性
Person.call(this,name,age);
// 自身属性定义
this.grade=grade;
}
// 修正原型链
Student.prototype=Object.create(Person.prototype);
// 子类的方法定义
Student.prototype.sayHelloToTeacher= function(teacher){
console.log("Hello!",teacher);
};
let student = new Student("小明","12","6");
console.log(Object.keys(student)); //[ 'name', 'age', 'grade' ]
student.sayHello(); //Hello!
student.sayHelloToTeacher("Mr. Wang"); //Hello! Mr. Wang
console.log(student instanceof Person); //true
console.log(student instanceof Student); //true