JavaScript 中的 this 和 arguments

this 到底指的是什麼

首先咱們知道函數的兩種調用方式:javascript

function sum(a, b) {
    return a + b
}

// 第一種方式
sum(1, 2)  // 3

// 第二種方式
sum.call(undefined, 1, 2)  // 3
複製代碼

若是函數以 .call() 的方式調用,那麼其實 this 一般指的就是第一個參數。暫時不討論以 () 的方式調用。java

可是須要注意的是:數組

  1. 當第一個參數爲 undefinednull 或空時,在非嚴格模式下,this 會自動指向全局 window 對象。函數

    // 非嚴格模式
    function fn() {
        console.log(this)
    }
    fn.call()  // 全局 window 對象
    fn.call(undefined)  // 全局 window 對象
    fn.call(null)  // 全局 window 對象
    
    // 使用嚴格模式
    function fn() {
     'use strict'
        console.log(this)
    }
    fn.call()  // undefined
    fn.call(undefined)  // undefined
    fn.call(null)  // null
    複製代碼
  2. 當第一個參數爲 NumberStringBoolean 類型時,在非嚴格模式下,this 會指向對應類型的包裝對象。ui

    // 非嚴格模式
    function fn() {
        console.log(typeof this)
    }
    fn.call(1)  // "object"
    fn.call('hello')  // "object"
    fn.call(true)  // "object"
    
    // 使用嚴格模式
    function fn() {
     'use strict'
        console.log(this)
    }
    fn.call(1)  // 1
    fn.call('hello')  // "hello"
    fn.call(true)  // true
    複製代碼

arguments

仍是最上面的例子。this

若是函數以 () 的方式調用,那麼 arguments 就是由全部參數組成的僞數組。spa

若是函數以 .call() 的方式調用,那麼 arguments 指的就是第二個及以後的參數組成的僞數組。code

須要注意的是,在非嚴格模式下,arguments 能夠被修改。對象

// 非嚴格模式
function sum(a, b) {
    arguments[0] = 4
    arguments[1] = 6
    return a + b
}
sum(1, 2)  // 10
sum.call(undefined, 1, 2)  // 10

// 嚴格模式
function sum(a, b) {
 'use strict'
    arguments[0] = 4
    arguments[1] = 6
    return a + b
}
sum(1, 2)  // 3
sum.call(undefined, 1, 2)  // 3
複製代碼
相關文章
相關標籤/搜索