JS 中的 this 和 arguments

917 阅读1分钟

this

在 JavaScript 中, 函数有两种调用方式:

function sum(x, y) {
    return x + y
}

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

// 第二种方式
sum.call(undefined, 1, 2)    // 3

第一种方式是常用的方法调用函数,第二种是使用 call() 方法调用函数,在使用后者调用函数时,第一个参数便是 this 值。

全局环境

无论是否在严格模式下,在全局执行环境中(在任何函数体外部)this 都指向全局对象。

// 在浏览器中, window 对象同时也是全局对象
console.log(this === window)    // true

a = 37
console.log(window.a)    // 37

this.b = "你好"
console.log(window.b)    // "你好"
console.log(b)           // "你好"

函数(运行内)环境

因为下面的代码不在严格模式下,且 this 的值不是由该调用设置的,所以 this 的值默认指向全局对象。

function f1(){
  return this
}
//在浏览器中:
f1() === window     //在浏览器中,全局对象是window

然而,在严格模式下,this 将保持他进入执行环境时的值,所以下面的 this 将会默认为 undefined

function f2(){
  "use strict"    // 这里是严格模式
  return this
}

f2() === undefined    // true

arguments

还是最上面的例子。
如果函数以 () 的方式调用,那么 arguments 就是由所有参数组成的伪数组。
如果函数以 call() 的方式调用,那么 arguments 指的就是第二个及之后的参数组成的伪数组。
需要注意的是,在非严格模式下,arguments 可以被修改。

// 非严格模式
function sum(x, y) {
    arguments[0] = 100
    arguments[1] = 100
    return x + y
}
sum(1, 2)  // 200
sum.call(undefined, 1, 2)  // 200

// 严格模式
function sum(x, y) {
    'use strict'
    arguments[0] = 100
    arguments[1] = 100
    return x + y
}
sum(1, 2)  // 3
sum.call(undefined, 1, 2)  // 3