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
复制代码
相关文章
相关标签/搜索