美文网首页
关于 JavaScript 中 this 的指向

关于 JavaScript 中 this 的指向

作者: 奕玄 | 来源:发表于2021-07-09 13:13 被阅读0次

🎯总结

  • 全局环境 ➡️ window
  • 普通函数 ➡️ window 或 undefined
  • 构造函数 ➡️ 构造出来的实例
  • 箭头函数 ➡️ 定义时外层作用域中的 this
  • 对象的方法 ➡️ 该对象
  • call()、apply()、bind() ➡️ 第一个参数

全局环境

无论是否在严格模式下,this 均指向 window 对象。

console.log(this === window)  // true
// 严格模式
'use strict'
console.log(this === window)  // true

普通函数

  1. 正常模式

    • this 指向 window 对象
    function test() {
      return this === window
    }
    
    console.log(test())  // true
    
  2. 严格模式

    • this 值为 undefined
    // 严格模式
    'use strict'
    
    function test() {
      return this === undefined
    }
    
    console.log(test())  // true
    

构造函数

函数作为构造函数使用时,this 指向构造出来的实例

function Test() {
  this.number = 1
}

let test1 = new Test()

console.log(test1.number)  // 1

箭头函数

函数为箭头函数时,this 指向函数定义时上一层作用域中的 this 值。

let test = () => {
  return this === window
}

console.log(test())  // true
let obj = {
  number: 1
}

function foo() {
  return () => {
    return this.number
  }
}

let test = foo.call(obj)

console.log(test())  // 1

对象的方法

函数作为对象的方法使用时,this 指向该对象

let obj = {
  number: 1,
  getNumber() {
    return this.number
  }
}

console.log(obj.getNumber())  // 1

call()、apply()、bind()

  • 调用函数的 call()、apply() 方法时,该函数的 this 均指向传入的第一个参数
  • 调用函数的 bind() 方法时,返回的新函数的 this 指向传入的第一个参数
let obj = {
  number: 1
}

function test(num) {
  return this.number + num
}

console.log(test.call(obj, 1))  // 2

console.log(test.apply(obj, [2]))  // 3

let foo = test.bind(obj, 3)
console.log(foo())  // 4

相关文章

  • 关于js函数中this的指向的问题

    @(javascript)[JavaScript中this的指向] 关于js函数中this的指向的问题 javas...

  • 关于 JavaScript 中 this 的指向

    ?总结 全局环境 ➡️ window 普通函数 ➡️ window 或 undefined 构造函数 ➡️ 构造出...

  • 关于JavaScript中的this指向问题

    this是面向对象语言中一个重要的关键字,理解并掌握该关键字的使用对于我们代码的健壮性及优美性至关重要。而java...

  • 关于javascript中this指向的问题

    1. 普通函数 this 指向window 2. 对象的方法 this指向的是"这个对象" 3.构造函数 this...

  • 【原创】this 指向问题总结

    JavaScript 中关于 this 指向的问题是一个令人比较头疼的问题,至于为什么要在 JavaScript ...

  • JavaScript中this指向

    文章较长,希望你耐心阅读并有所收获。 this指向 想必各位看客老爷搜索此问题,多多少少还是被this迷惑住了,今...

  • javascript中的this指向

    写在前面 本文转自深入浅出 JavaScript 中的 this 在java等面向对象的语言中,this关键字的含...

  • Javascript 中 this 的指向

    大家好,我是IT修真院武汉第10期学员,一枚正直、纯洁、善良的前端程序员。 今天给大家分享一下,修真院官网任务...

  • JavaScript中的this指向

    1.概念 在JavaScript中,this 是指当前函数中正在执行的上下文环境,因为这门语言拥有四种不同的函数调...

  • javascript中this的指向

    在面向对象的语言中(例如Java,C#等),this含义是明确且具体的,即指向当前对象。一般在编译期绑定。而在ja...

网友评论

      本文标题:关于 JavaScript 中 this 的指向

      本文链接:https://www.haomeiwen.com/subject/garfpltx.html