亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript 中this指向問題案例詳解

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

總結(jié)

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

全局環(huán)境

無論是否在嚴格模式下,this 均指向 window 對象。

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

普通函數(shù)

  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
      

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

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

function Test() {
  this.number = 1
}

let test1 = new Test()

console.log(test1.number)  // 1

箭頭函數(shù)

函數(shù)為箭頭函數(shù)時,this 指向函數(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

對象的方法

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

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

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

call()、apply()、bind()

  • 調(diào)用函數(shù)的 call()、apply() 方法時,該函數(shù)的 this 均指向傳入的第一個參數(shù)。
  • 調(diào)用函數(shù)的 bind() 方法時,返回的新函數(shù)的 this 指向傳入的第一個參數(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指向問題案例詳解的文章就介紹到這了,更多相關(guān)JavaScript 中this指向問題內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JS實現(xiàn)的簡單分頁功能示例

    JS實現(xiàn)的簡單分頁功能示例

    這篇文章主要介紹了JS實現(xiàn)的簡單分頁功能,涉及javascript事件響應(yīng)及頁面元素遍歷、動態(tài)構(gòu)造等相關(guān)操作技巧,需要的朋友可以參考下
    2018-08-08
  • JavaScript flash復制庫類 Zero Clipboard

    JavaScript flash復制庫類 Zero Clipboard

    開發(fā)中經(jīng)常會用到復制的功能,在 IE 下實現(xiàn)比較簡單。但要想做到跨瀏覽器比較困難了。
    2011-01-01
  • Js+Jq獲取URL參數(shù)的集中方法示例代碼

    Js+Jq獲取URL參數(shù)的集中方法示例代碼

    這篇文章主要介紹了Js+Jq獲取URL參數(shù)的集中方法,需要的朋友可以參考下
    2014-05-05
  • javascript中 try catch用法

    javascript中 try catch用法

    JS try catch語句一般在什么情況下使用?是必須使用的嗎?下面就讓小編來給大家介紹一下試用心得。
    2015-08-08
  • JS實現(xiàn)深度優(yōu)先搜索求解兩點間最短路徑

    JS實現(xiàn)深度優(yōu)先搜索求解兩點間最短路徑

    這篇文章主要為大家詳細介紹了JS實現(xiàn)深度優(yōu)先搜索求解兩點間最短路徑,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • 最新評論