arguments

Posted by Zxd on March 28, 2017

arguments

在函数被调用时,会自动在该函数内部生成一个名为 arguments的隐藏对象.该对象类似于数组,但除了长度之外没有任何数组属性.可以使用[]操作符获取函数调用时传递的实参.

1
2
3
4
(function () {  
console.log(arguments instanceof Array); // false
console.log(typeof(arguments)); // object
})();

转换为数组

1
2
3
4
5
6
7
8
9
//ES6
//方法1. 注意:对参数使用slice会阻止js引擎中的优化
let args = Array.prototype.slice.call(arguments);

let args = [].slice.call(arguments);

//方法2.
let args = Array.from(arguments);
let args = [...arguments];

属性

  • arguments.callee 指向当前执行的函数
  • arguments.length 实参长度(指向传递给当前函数的参数数量)
  • arguments.callee.length 形参长度

arguments.callee 引用当前正在运行的函数,给匿名函数提供了一种自我引用的方法

  • arguments.callee :初始值就是正被执行的Function对象,常用于匿名函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function a(x, y, z) {
//arguments.callee指向函数a(),arguments.callee.length==a.length;

console.log(arguments.callee.length); //3
console.log(arguments.length); //5

if (arguments.callee.length != arguments.length) {

//判断形参与实参个数是否相等,不相等则不执行
console.log(arguments.callee);
return false;
}
}
a(1,2,3,4,5);
1
2
3
4
5
6
7
8
9
function create() {
return function(n) {
if (n <= 1)
return 1;
return n * arguments.callee(n - 1);
};
}

var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)

Function.caller 返回调用指定函数的函数(调用函数的父函数)

  • 返回一个对函数的引用,该函数调用了当前函数
  • 非标特性,尽量不在生产环境中用它
  • 在一个函数调用另一个函数时,被调用函数会自动生成一个caller属性,指向调用它的函数对象,如果该函数当前未被调用,则Function.caller为null
1
2
3
4
5
6
7
8
9
10
11
function parentCheck() {
check("");
function check() {
subCheck();
function subCheck() {
console.log(arguments.callee); // function subCheck(){}
console.log(subCheck.caller.caller) //function parentCheck(){}
}
}
}
parentCheck();
  • 如果一个函数f是在全局作用域内被调用的,则f.caller为null,相反,如果一个函数是在另外一个函数作用域内被调用的,则f.caller指向调用它的那个函数.

  • 该属性的常用形式arguments.callee.caller替代了被废弃的 arguments.caller.

注意,callee和caller两个属性只有当函数在执行时才有用

  • function.caller中 function是正在被执行的函数