在 JavaScript 中,有多种方法可以改变 “this” 的指向。
- 使用 call() 或 apply() 方法。这两个方法都立即调用函数,并且将第一个参数作为新的 “this” 值。区别: call() 方法接收一系列参数,而 apply() 方法接收一个数组,所以可以将这些参数作为第二个参数传递。例如:
function myFunc(a, b) { console.log(this, a, b); } const obj = { myProp: 'hello' }; myFunc.call(obj, 1, 2); // 输出 { myProp: 'hello' } 1 2 myFunc.apply(obj, [3, 4]); // 输出 { myProp: 'hello' } 3 4
- 使用 bind() 方法。bind() 方法返回一个新函数,其 “this” 值被绑定为传递给 bind() 方法的第一个参数。例如:
function myFunc() { console.log(this); } const obj = { myProp: 'hello' }; const boundFunc = myFunc.bind(obj); boundFunc(); // 输出 { myProp: 'hello' }
- 使用箭头函数。箭头函数的 “this” 始终指向定义函数时的 “this”,而不是调用函数时的 “this”。例如:
const obj = { myProp: 'hello' }; const myFunc = () => { console.log(this); } myFunc.call(obj); // 输出全局对象,因为箭头函数中的 "this" 绑定在定义时,而不是在调用时。