最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript 中this指向問(wèn)題案例詳解

 更新時(shí)間:2021年08月30日 15:18:33   作者:奕玄  
這篇文章主要介紹了JavaScript 中this指向問(wèn)題案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

總結(jié)

  • 全局環(huán)境 ➡️ window
  • 普通函數(shù) ➡️ window 或 undefined
  • 構(gòu)造函數(shù) ➡️ 構(gòu)造出來(lái)的實(shí)例
  • 箭頭函數(shù) ➡️ 定義時(shí)外層作用域中的 this
  • 對(duì)象的方法 ➡️ 該對(duì)象
  • call()、apply()、bind() ➡️ 第一個(gè)參數(shù)

全局環(huán)境

無(wú)論是否在嚴(yán)格模式下,this 均指向 window 對(duì)象。

console.log(this === window)  // true
// 嚴(yán)格模式
'use strict'
console.log(this === window)  // true

普通函數(shù)

  1. 正常模式
    • this 指向 window 對(duì)象
    • function test() {
        return this === window
      }
      
      console.log(test())  // true
      
  2. 嚴(yán)格模式
    • this 值為 undefined
    • // 嚴(yán)格模式
      'use strict'
      
      function test() {
        return this === undefined
      }
      
      console.log(test())  // true
      

構(gòu)造函數(shù)

函數(shù)作為構(gòu)造函數(shù)使用時(shí),this 指向構(gòu)造出來(lái)的實(shí)例。

function Test() {
  this.number = 1
}

let test1 = new Test()

console.log(test1.number)  // 1

箭頭函數(shù)

函數(shù)為箭頭函數(shù)時(shí),this 指向函數(shù)定義時(shí)上一層作用域中的 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

對(duì)象的方法

函數(shù)作為對(duì)象的方法使用時(shí),this 指向該對(duì)象。

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

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

call()、apply()、bind()

  • 調(diào)用函數(shù)的 call()、apply() 方法時(shí),該函數(shù)的 this 均指向傳入的第一個(gè)參數(shù)。
  • 調(diào)用函數(shù)的 bind() 方法時(shí),返回的新函數(shù)的 this 指向傳入的第一個(gè)參數(shù)。
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

到此這篇關(guān)于JavaScript 中this指向問(wèn)題案例詳解的文章就介紹到這了,更多相關(guān)JavaScript 中this指向問(wèn)題內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

湛江市| 合川市| 德阳市| 神木县| 徐闻县| 都匀市| 措勤县| 水城县| 永川市| 清新县| 重庆市| 安溪县| 临邑县| 策勒县| 邛崃市| 龙州县| 岗巴县| 历史| 平远县| 鸡西市| 江达县| 诏安县| 晋宁县| 邳州市| 横峰县| 岑巩县| 沿河| 大港区| 乐至县| 新宾| 自贡市| 佛冈县| 水富县| 洪江市| 上饶县| 宿迁市| 三河市| 孟州市| 乌苏市| 乐昌市| 阜康市|