arguments之与ES6语法冲突

function test(a,b){
    arguments[0] = 5;
    console.log(a) //5
}

test(1,2)

function test(a,b){
    a = 5;
    console.log(arguments[0]) //5
}

test(1,2)

从上面两个例子我们可以知道arguments和实参是映射关系,大白话说就是一方改变另一方也会跟着改变

但用上ES6语法arguments和实参的映射关系就被打破了,请看下面例子

function test(a = 6,b){
    arguments[0] = 5;
    console.log(a) // 1
}

test(1,2)

function test({a,b}){
    arguments[0] = 5;
    console.log(a) //1
}

test({a:1,b:2})

function test(...rest){
    arguments[0] = 5;
    console.log(rest) //[1,2]
}

test(1,2)

最后严格模式也会使映射关系被破坏
function test(a ,b){
    "use strict"
    arguments[0] = 5;
    console.log(a) //1
}

test(1,2)

那到底为什么会产生这种问题呢?
其实是w3c组织在有意的弱化arguments的作用,从严格模式映射关系被破坏就可以看出来,官方更愿意我们开发者用剩余参数收集语法(…),这样拿到的就直接是一个数组,而arguments是类数组,要遍历它还要转换为数组,性能也会被影响


版权声明:本文为m0_46365130原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。