直接调用
- this绑定规则:在非严格模式下,直接调用函数时,
this
绑定到全局对象(浏览器环境中是 window
,Node.js 环境中是 global
);在严格模式下,this
绑定到 undefined
。
- 示例:
// 非严格模式
function directCall() {
console.log(this);
}
directCall(); // 在浏览器中输出 window 对象
// 严格模式
function strictDirectCall() {
'use strict';
console.log(this);
}
strictDirectCall(); // 输出 undefined
作为对象方法调用
- this绑定规则:当函数作为对象的方法被调用时,
this
绑定到该对象。
- 示例:
const obj = {
name: 'example',
method: function() {
console.log(this.name);
}
};
obj.method(); // 输出 'example'
通过构造函数调用
- this绑定规则:通过构造函数调用时,
this
绑定到新创建的对象实例。新创建的对象会继承构造函数的原型属性和方法。
- 示例:
function Constructor() {
this.value = 42;
}
const instance = new Constructor();
console.log(instance.value); // 输出 42
使用 call/apply/bind 调用
- this绑定规则:
call
、apply
和 bind
方法都允许显式地指定函数调用时 this
的绑定对象。
call
方法接受多个参数,第一个参数是要绑定的 this
对象,后面的参数依次作为函数的参数。
apply
方法第一个参数也是要绑定的 this
对象,但第二个参数是一个包含函数参数的数组。
bind
方法返回一个新的函数,新函数的 this
被绑定到 bind
方法的第一个参数,并且可以传递额外的参数。
- 示例:
function showValue() {
console.log(this.value);
}
const obj1 = { value: 10 };
const obj2 = { value: 20 };
// call 方法
showValue.call(obj1); // 输出 10
// apply 方法
showValue.apply(obj2); // 输出 20
// bind 方法
const boundShowValue = showValue.bind(obj1);
boundShowValue(); // 输出 10