在 javascript 中,原型方法里的 this 指向取决于调用该方法的对象。如果通过实例调用(如 obj.method()),this 指向该实例;如果是直接引用函数或作为回调传递,则可能丢失上下文,指向全局对象或 undefined。

通过实例调用时 this 指向谁
当使用实例调用原型方法时,this 自动绑定到该实例。这是最常见的情况,开发者无需额外处理即可访问实例属性。

function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
const p = new Person('Alice');
p.greet(); // 输出: Hello, Alice运行上述代码,控制台会输出 Hello, Alice。这里 p.greet() 的调用方式确保了 this 指向 p 实例。
立即学习“Java免费学习笔记(深入)”;
直接引用或回调中 this 指向谁
如果将原型方法赋值给变量或直接作为回调函数传递,this 会丢失对实例的绑定。在非严格模式下,它指向全局对象(浏览器中为 window);在严格模式下,它变为 undefined。

function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(this === window ? 'Global' : this.name);
};
const p = new Person('Bob');
const fn = p.greet;
fn(); // 非严格模式输出: Global运行上述代码,由于 fn() 是独立调用,this 不再指向 p。解决方法是使用 bind、call 或箭头函数来保留上下文。
使用 bind 修复 this 指向的具体问题
针对上述回调中 this 丢失的问题,可以使用 bind 方法显式绑定 this。这将返回一个新函数,其 this 始终指向指定的对象。
const boundGreet = p.greet.bind(p); boundGreet(); // 输出: Bob
通过 bind,我们创建了 boundGreet,它内部固定了 this 为 p。无论之后如何调用 boundGreet,this 都会正确指向 p 实例,从而解决上下文丢失问题。


















