Javascript 中的继承基于原型链。
js
// 创建一个父类
class Parent {
static staticMethod() {
console.log('This is a static method on Parent class')
}
constructor(name) {
this.name = name
}
greet() {
console.log('Hello, my name is ' + this.name)
}
}
// 创建一个子类
class Child extends Parent {
constructor(name, age) {
// 调用父类构造函数
super(name)
this.age = age
}
// 为子类添加方法
introduce() {
console.log('I am ' + this.name + ' and I am ' + this.age + ' years old.')
}
}
// 使用继承的类
const childInstance = new Child('Alice', 10)
childInstance.greet() // 输出: Hello, my name is Alice
childInstance.introduce() // 输出: I am Alice and I am 10 years old.
Child.staticMethod() // 输出: This is a static method on Parent class
Object.getPrototypeOf(Child) === Parent // true
Object.getPrototypeOf(childInstance) === Child.prototype // true
Object.getPrototypeOf(Child.prototype) === Parent.prototype // true
当我们访问 Child.staticMethod() 时,JavaScript 引擎会按照以下顺序查找方法:
- 在 Child 类本身查找
staticMethod方法。 - 如果没有找到,则在 Child 的原型(即 Parent 类)上查找
staticMethod方法。 - 找到后执行它。
这就是为什么 Child 能调用 Parent 的静态方法的原因。
当我们访问 childInstance.greet() 时,JavaScript 引擎会按照以下顺序查找方法:
- 在 childInstance 对象本身查找
greet方法。 - 如果没有找到,则在 childInstance 的原型(即 Child.prototype)上查找
greet方法。 - 如果仍然没有找到,则在 Child.prototype 的原型(即 Parent.prototype)上查找
greet方法。 - 找到后执行它。
这就是为什么 childInstance 能调用 Parent 的实例方法的原因。