解释 `this` 关键字并介绍他是如何工作的?

本贴最后更新于 1852 天前,其中的信息可能已经物是人非

2019-02-21

回答

this 关键字是函数执行过程中用于表示上下文的对象。传统的常规函数可以使用 call()apply()bind() 方法来改变他们的 this 值。箭头函数会隐式的绑定 this,因此无论其上下文是否使用 call() 进行设置,他的上下文引用都是其词法环境中的上下文。

这有一些关于 this 是如何工作的常见例子:

Object literals

如果使用对象本身调用其内部函数时,该函数的 this 为对象本身。
如果对象的属性被设置为 this,他并不会指向对象本身。

var myObject = {
  property: this,
  regularFunction: function() {
    return this
  },
  arrowFunction: () => {
    return this
  },
  iife: (function() {
    return this
  })()
}
myObject.regularFunction() // {property: Window, regularFunction: ƒ, arrowFunction: ƒ, iife: Window}
myObject["regularFunction"]() // {property: Window, regularFunction: ƒ, arrowFunction: ƒ, iife: Window}
myObject.property // Window
myObject.arrowFunction() // Window
myObject.iife // Window
const regularFunction = myObject.regularFunction
regularFunction() // Window

Event listeners

this 为监听事件的元素

document.body.addEventListener("click", function() {
  console.log(this) // <body>...</body>
}) 

Constructors

this 为新创建的对象。

class Example {
    constructor(a) {
        this.a = a
        console.log(this)
    }
}
const example = new Example(1) // Example {a: 1}
const example2 = new Example(2) // Example {a: 2}

Manual

使用 call()apply()this 为传入的第一个参数。

var myFunction = function() {
  return this
}
myFunction() // Window
myFunction.call({ customThis: true }) // { customThis: true } 

Unwanted this

因为 this 会根据他的作用域而变化,所以在传统的常规函数中他可能会产生不期望的值。

var obj = {
  arr: [1, 2, 3],
  doubleArr() {
    return this.arr.map(function(value) {
      return this.double(value)
    })
  },
  double() {
    return value * 2
  }
}
obj.doubleArr() // Uncaught TypeError: this.double is not a function

加分回答

  • 在非严格模式下,全局的 this 是全局对象(浏览器中的 Window)。而在严格模式下,全局的 thisundefined
  • Function.prototype.callFunction.prototype.apply 可以设置 this 的上下文为该方法中的第一个参数。call 中第一个参数以后的参数与 Function 中的参数保持一致;apply 中的第二个参数为一个数组,Function 中的参数将被输入到这个数组中。
    Function.prototype.bind 返回一个新函数,该函数将此上下文强制为第一个不能被其他函数更改的参数。
  • Function.prototype.bind 返回一个新函数,该新函数将第一个参数作为 this 的上下文。这个新函数后面无论被如何调用,他的 this 都不会被改变。
function f(){
  return this.a;
}
var g = f.bind({a:"azerty"});
console.log(g()); // azerty
var h = g.bind({a:'yoo'}); 
console.log(h()); // azerty
  • 如果函数要求他的 this 上下文可以基于他的调用方式进行修改,你必须要使用 function 关键字。当你希望 this 为词法环境上下文时,请使用箭头函数。

返回总目录

每天 30 秒

  • 30Seconds

    📙 前端知识精选集,包含 HTML、CSS、JavaScript、React、Node、安全等方面,每天仅需 30 秒。

    • 精选常见面试题,帮助您准备下一次面试
    • 精选常见交互,帮助您拥有简洁酷炫的站点
    • 精选有用的 React 片段,帮助你获取最佳实践
    • 精选常见代码集,帮助您提高打码效率
    • 整理前端界的最新资讯,邀您一同探索新世界
    488 引用 • 383 回帖 • 10 关注
  • JavaScript

    JavaScript 一种动态类型、弱类型、基于原型的直译式脚本语言,内置支持类型。它的解释器被称为 JavaScript 引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在 HTML 网页上使用,用来给 HTML 网页增加动态功能。

    710 引用 • 1173 回帖 • 198 关注
  • 面试

    面试造航母,上班拧螺丝。多面试,少加班。

    324 引用 • 1395 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...