javascript 中 this 在继承中指向父类怎么配置

构造函数继承中如何绑定 this
通过 call 或 apply 调用父类构造函数,将子类实例的 this 传入,实现属性继承。

function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
const child = new Child('Alice', 5);
console.log(child.name); // Alice
console.log(child.age); // 5
预期结果:child.name 为 'Alice',child.age 为 5。this 正确指向 child 实例。
原型链继承中 this 的行为
原型链继承不直接涉及 this 绑定,但方法中的 this 仍指向调用该方法的实例。
在代码库出现结构漂移之前,扫描JS或TS代码库中的禁止导入、循环依赖、孤立模块和其他依赖规则违规情况。

function Parent() {}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent();
const child = new Child();
child.name = 'Bob';
child.sayName(); // Bob
预期结果:sayName 输出 'Bob',this 指向 child 实例。
基于 Child 实例调用 sayName 时 this 指向的具体问题
当通过实例调用继承的方法时,this 始终指向该实例,而非父类或原型对象。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










