- 全局作用域调用:
- 代码:
functionA();
this
指向:在非严格模式下,全局作用域中调用函数,this
指向全局对象(在浏览器中是window
,在Node.js中是global
)。在严格模式下,全局作用域中调用函数,this
指向undefined
。
- 对象方法调用:
const obj = {
func: functionA
};
obj.func();
- 使用
call
改变this
指向:
const newThis = {name: 'newObj'};
functionA.call(newThis);
this
指向:call
方法的第一个参数,即newThis
对象。
- 使用
apply
改变this
指向:
const newThis = {name: 'newObj'};
functionA.apply(newThis);
this
指向:apply
方法的第一个参数,即newThis
对象。apply
与call
的区别在于第二个参数,call
后续参数是逐个列出,而apply
第二个参数是一个数组(或类数组对象)。
- 使用
bind
改变this
指向:
const newThis = {name: 'newObj'};
const boundFunction = functionA.bind(newThis);
boundFunction();
this
指向:bind
方法返回一个新函数,这个新函数内部的this
被绑定为bind
方法的第一个参数,即newThis
对象。bind
方法不会立即执行函数,而是返回一个新函数,新函数被调用时,this
指向绑定的对象。