什么是 PointAt 和 PointTo?
在 JavaScript 开发中,我们常遇到 this 指向的问题。
虽然 “PointAt” 和 “PointTo” 并非官方术语,但它们可以形象地描述两种关键机制:
- PointAt(主动指定):通过
call、apply、bind显式改变函数内部this的指向。 - PointTo(被动绑定):函数在定义或调用时,由上下文环境隐式决定
this的值,如普通函数、箭头函数、对象方法等。
PointAt:显式绑定 this
使用 call、apply 或 bind 可以“指向”一个特定对象作为 this:
const obj = { name: 'Alice' };
function greet() {
console.log(`Hello, I'm ${this.name}`);
}
greet.call(obj); // Hello, I'm Alice
greet.apply(obj); // 同上
const boundGreet = greet.bind(obj);
boundGreet(); // Hello, I'm Alice
PointTo:隐式绑定与词法作用域
不同函数类型对 this 的处理方式不同:
- 普通函数:调用时由调用方式决定(如
obj.method()中this === obj)。 - 箭头函数:没有自己的
this,它“指向”(PointTo)定义时所在的作用域(词法作用域)。
const person = {
name: 'Bob',
regular() {
console.log(this.name); // Bob
},
arrow: () => {
console.log(this.name); // undefined(在浏览器中可能是 window.name)
}
};
person.regular();
person.arrow();
交互演示
点击按钮查看不同调用方式下 this 的输出: