解释 `this` 关键字可以绑定的不同方式
主题
闭合JavaScript
在GitHub上编辑
TL;DR
this
关键字在 JavaScript 中可以通过几种方式绑定:
- 默认绑定:在非严格模式下,
this
指向全局对象(在浏览器中是 window)。在严格模式下,this
是undefined
。 - 隐式绑定:当一个函数作为对象的方法被调用时,
this
指向该对象。 - 显式绑定:使用
call
、apply
或bind
方法显式设置this
。 - new 绑定:当一个函数与
new
关键字一起用作构造函数时,this
指向新创建的对象。 - 箭头函数:箭头函数没有自己的
this
,并从周围的词法环境继承this
。
默认绑定
在非严格模式下,如果一个函数在没有任何上下文的情况下被调用,this
指向全局对象(在浏览器中是 window)。在严格模式下,this
是 undefined
。
function showThis() {console.log(this);}showThis(); // 在非严格模式下:window,在严格模式下:undefined
隐式绑定
当一个函数作为对象的方法被调用时,this
指向该对象。
const obj = {name: 'Alice',greet: function () {console.log(this.name);},};obj.greet(); // 'Alice'
显式绑定
使用 call
、apply
或 bind
方法,你可以显式地设置 this
。
使用 call
function greet() {console.log(this.name);}const person = { name: 'Bob' };greet.call(person); // 'Bob'
使用 apply
function greet(greeting) {console.log(greeting + ', ' + this.name);}const person = { name: 'Charlie' };greet.apply(person, ['Hello']); // 'Hello, Charlie'
使用 bind
function greet() {console.log(this.name);}const person = { name: 'Dave' };const boundGreet = greet.bind(person);boundGreet(); // 'Dave'
New 绑定
当一个函数与 new
关键字一起用作构造函数时,this
指的是新创建的对象。
function Person(name) {this.name = name;}const person = new Person('Eve');console.log(person.name); // 'Eve'
箭头函数
箭头函数没有自己的 this
,并从周围的词法上下文中继承 this
。
const obj = {firstName: 'Frank',greet: () => {console.log(this.firstName);},};obj.greet(); // undefined, because `this` is inherited from the global scope