
深入理解ES6父子继承:this指向和执行顺序
以下代码演示了ES6中父子类的继承,以及this指向和执行顺序的细节:
<code class="javascript">class Parent {
constructor() {
console.log('Parent constructor', this.name); // 1
this.init(); // 2
this.logNum = this.logNum.bind(this); // 3
}
name = (() => { // 4
console.log('Parent name init'); // 5
return 'Parent'; // 6
})();
num = -1;
init() {
console.log('Parent init', this.name); // 7
}
logNum() {}
}
class Child extends Parent {
constructor() {
console.log('Child constructor'); // 8
super(); // 9
console.log('super exec finish', this.num); // 10
}
name = 'Child';
num = (() => { // 11
console.log('Child num init'); // 12
return 99; // 13
})();
init() {
console.log('Child init', this.name); // 14
super.init(); // 15
this.num = 10; // 16
}
logNum() {
console.log(this.num); // 17
}
}
const { logNum } = new Child();
logNum(); // 18</code>输出结果:
<code>Child constructor Parent name init Parent constructor Parent Child init Child Parent init Parent Child num init super exec finish 99 99</code>
关键点分析:
类字段初始化: 在实例化Child之前,Parent类的静态字段name就已经通过立即执行函数表达式(IIFE)初始化为'Parent'。这发生在任何构造函数执行之前。
super()调用: Child的构造函数中,super()调用必须在this被使用之前。super()调用会执行Parent的构造函数。
this指向: 在Parent和Child的构造函数以及init方法中,this始终正确地指向当前实例(Child实例)。
执行顺序: 代码的执行顺序按照数字标号所示,清晰地展现了类字段初始化、super()调用、父类构造函数执行、子类构造函数执行的顺序。
实例属性初始化: Parent类的实例属性在Parent构造函数中初始化;Child类的实例属性在Child构造函数中,super()调用之后初始化。Child的num属性在super()之后初始化,因为super()调用会先执行父类的构造函数。
方法绑定: this.logNum = this.logNum.bind(this); 这行代码确保了logNum方法中的this始终指向正确的实例,即使在不同的上下文中调用。
通过以上分析,可以明确理解ES6父子类继承中this指向和执行顺序的机制,避免常见的误解。 super()的调用时机和类字段的初始化顺序是理解关键。
以上就是ES6父子继承中this指向和执行顺序究竟是怎样的?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号