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指向本身。this

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.spa

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.prototype

  Examplescode

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
相關文章
相關標籤/搜索