欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript 中this指向問題案例詳解

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

總結(jié)

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

全局環(huán)境

無論是否在嚴(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)造出來的實(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指向問題案例詳解的文章就介紹到這了,更多相關(guān)JavaScript 中this指向問題內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

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

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

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

    JavaScript flash復(fù)制庫類 Zero Clipboard

    開發(fā)中經(jīng)常會(huì)用到復(fù)制的功能,在 IE 下實(shí)現(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實(shí)現(xiàn)深度優(yōu)先搜索求解兩點(diǎn)間最短路徑

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

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