继承是面向对象中一个重要的概念,通过继承这种特性就能够抽象出来相似类型之间重复的地方。
function Person (name) { // 构造函数
console.log('name:', name)
this.name = name
}
Person.prototype.say = function () { // 实例方法
console.log(`hi, my name is ${this.name}`)
}
Person.create = function (name) { // 静态方法
return new Person(name)
}
function Student (name, number) { // 构造函数
/**
* 在子类的构造函数里使用 call 或 apply,
* 复制父类的实例属性给子类(没用到原型)
*/
Person.call(this, name);
const say = arguments.callee.prototype.constructor.prototype.say;
this.number = number;
this.hello = function () {
say();
console.log(`my school number is ${this.number}`);
console.log(this.name)
}
}
Student.prototype = new Person()
const leo = new Student('leo', 1001)
leo.hello()
在 ES2015 之前大多数情况都会使用原型的方式去实现继承,而在 ES2015 中它实现了一个专门用于类继承的关键词 extends 。
class Person {
constructor (name) { // 构造函数
this.name = name
}
static create (name) { // 静态方法
return new Person (name)
}
say () { // 实例方法
console.log(`hi, my name is ${this.name}`)
}
}
class Student extends Person {
constructor (name, number) {
super(name) // 始终指向父类,调用它就是调用了父类的构造函数
this.number = number;
}
hello () {
super.say();
console.log(`my shoole number is ${this.number}`)
}
}
const leo = new Student('leo', 1001);
leo.hello();