华域联盟 JAVA JavaScript 中this指向问题案例详解

JavaScript 中this指向问题案例详解

总结

  • 全局环境 ️ 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

到此这篇关于JavaScript 中this指向问题案例详解的文章就介绍到这了,更多相关JavaScript 中this指向问题内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » JavaScript 中this指向问题案例详解

转载请保留出处和原文链接:https://www.cnhackhy.com/80664.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部