使用arguments伪参数作为可写事物

Alm*_* Do 7 javascript arguments function

在javascript中,有arguments伪参数这样的东西,它允许动态地与函数参数交互.现在,当我正在听关于javascript基本事物和标准的讲座时,有一句话:

"不要arguments用作可写结构,总是把它视为只读的东西"

我从来没有arguments在那里写过,所以这对我来说不是问题 - 但是,真的 - 我想问问我

问题:在使用arguments写作时是否存在任何实际用例?如果没有,那么为什么不arguments应该用它来写呢?

Den*_*ret 7

让我们假设你疯了,你想要自定义console.log这样做

console.log("window.innerWidth");
Run Code Online (Sandbox Code Playgroud)

会记录

window.innerWidth = 775 
Run Code Online (Sandbox Code Playgroud)

这看起来比做起来更方便

console.log("window.innerWidth =", window.innerWidth);
Run Code Online (Sandbox Code Playgroud)

您可以通过构建新数组"正确"执行此操作,也可以重用arguments:

(function(){
  var stdlog = console.log;
  console.log = function(){
    if (arguments.length===1 && typeof arguments[0]==="string") {
      try {
       arguments[1] = eval('('+arguments[0]+')');
       arguments[0] += " =";
       arguments.length = 2;
      } catch (e) {} // in case it can't be evaled, do the normal thing
    }
    stdlog.apply(console, arguments);
  };
})();

console.log("window.innerWidth"); // window.innerWidth =  775 
console.log("Hello"); // Hello
Run Code Online (Sandbox Code Playgroud)

重用arguments这里本来没有建立一个数组,当你不需要它的优势和不重复呼叫stdlog.没有那个黑客,代码就会变得不那么干.

现在,为什么你不应该做这样的事情:

  • arguments尚未被设计成类似阵列可写,我必须设置arguments.length显式
  • 简单地切片arguments对象并传递结果数组相当容易,因为 无论如何没有可访问的函数需要参数对象.
  • 以某种方式使用本机结构它实际上不打算使用可能会导致未来的不兼容性
  • 它会阻止优化.JS引擎做了很多优化,没有这些优化,许多现代Web应用程序将无法实现.他们在极少数情况下放弃优化,其中一些与参数有关
  • 它在严格模式下不起作用而且不严格.你是否真的想要一个功能,如果添加(可能通过在缩小过程中连接文件)到一个文件有一个微妙的不同的行为"use strict"?

这是严格模式改变一切的情况:

function incrNumber(v) {
  arguments[0]++;
  console.log(v)
}
Run Code Online (Sandbox Code Playgroud)

在严格模式下,将记录传递的值.在非严格模式下,将记录递增的值.这就是指定的行为.