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 实例。
立即学习“Java免费学习笔记(深入)”;
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
原型链继承中 this 的行为
原型链继承不直接涉及 this 绑定,但方法中的 this 仍指向调用该方法的实例。

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 始终指向该实例,而非父类或原型对象。

















