JS 中的 this 和 arguments

this

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

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

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

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

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

全局环境

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

// 在浏览器中, 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 将会默认为 undefinedui

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

f2() === undefined    // true
复制代码

arguments

仍是最上面的例子。
若是函数以 () 的方式调用,那么 arguments 就是由全部参数组成的伪数组。
若是函数以 call() 的方式调用,那么 arguments 指的就是第二个及以后的参数组成的伪数组。
须要注意的是,在非严格模式下,arguments 能够被修改。this

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