Javascript函数的参数arguments

arguments
  Description
    在所有的函数中有一个arguments对象,arguments对象指向函数的参数,arguments object is an Array-like object,除了length,不具备数组的其他属性。
    访问: var a = arguments[0];
    arguments可以改变: arguments[1] = 'new value';
    arguments转换为一个真实的数组:
      var args = Array.prototype.slice.call(arguments);
      var args = [].slice.call(arguments);
      var args = Array.from(arguments);
      var args = [...arguments];

  Properties
    arguments.callee
      Reference to the currently executing function.
      指向当前正在执行的函数的函数体。在匿名函数中很有用。

function fun(){
    console.log(arguments.callee == fun);//true
    console.log(arguments.callee);
/*
function fun(){
    console.log(arguments.callee == fun);//true
    console.log(arguments.callee);
}
*/
}
fun();
var global = this;
var sillyFunction = function(recursed) {
if (!recursed) { return arguments.callee(true); }
if (this !== global) {
console.log('This is: ' + this);
} else {
console.log('This is the global');
}
}
sillyFunction();//This is: [object Arguments]

    使用arguments.callee在匿名递归函数中:
      一个递归函数必须能够指向它自己,通过函数名可以指向自己,但是在匿名函数没有函数名,所以使用arguments.callee指向自己。

function create() {
return function(n) {
if (n <= 1)
return 1;
return n * arguments.callee(n - 1);
};
}
var result = create()(5); 
console.log(result);// returns 120 (5 * 4 * 3 * 2 * 1)

    arguments.caller
      Reference to the function that invoked the currently executing function.这个属性已经被移出了,不再工作,但是仍然可以使用Function.caller.

function whoCalled() {
if (arguments.caller == null)
console.log('I was called from the global scope.');
else
console.log(arguments.caller + ' called me!');
}
whoCalled();//I was called from the global scope.
function whoCalled() {
if (whoCalled.caller == null)
console.log('I was called from the global scope.');
else
console.log(whoCalled.caller + ' called me!');
}
whoCalled();//I was called from the global scope.
function whoCalled() {
if (whoCalled.caller == null)
console.log('I was called from the global scope.');
else
console.log(whoCalled.caller + ' called me!');
}
function meCalled(){
whoCalled();
}
meCalled();
/*
function meCalled(){
whoCalled();
} called me!
*/

    arguments.length
      Reference to the number of arguments passed to the function.
    arguments[@@iterator]
      Returns a new Array Iterator object that contains the values for each index in the arguments.

  Examples

function myConcat(separator) {
var args = Array.prototype.slice.call(arguments, 1);
return args.join(separator);
}
myConcat(', ', 'red', 'orange', 'blue');// returns "red, orange, blue"

function bar(a = 1) { 
arguments[0] = 100;
return a;
}
bar(10); // 10

function zoo(a) { 
arguments[0] = 100;
return a;
}
zoo(10); // 100

猜你喜欢

转载自www.cnblogs.com/skorzeny/p/6527096.html