Alm*_* Do 7 javascript arguments function
在javascript中,有arguments伪参数这样的东西,它允许动态地与函数参数交互.现在,当我正在听关于javascript基本事物和标准的讲座时,有一句话:
"不要arguments用作可写结构,总是把它视为只读的东西"
我从来没有arguments在那里写过,所以这对我来说不是问题 - 但是,真的 - 我想问问我
问题:在使用arguments写作时是否存在任何实际用例?如果没有,那么为什么不arguments应该用它来写呢?
让我们假设你疯了,你想要自定义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对象并传递结果数组相当容易,因为 无论如何没有可访问的函数需要参数对象."use strict"?这是严格模式改变一切的情况:
function incrNumber(v) {
arguments[0]++;
console.log(v)
}
Run Code Online (Sandbox Code Playgroud)
在严格模式下,将记录传递的值.在非严格模式下,将记录递增的值.这就是指定的行为.
| 归档时间: |
|
| 查看次数: |
223 次 |
| 最近记录: |