当前位置:网站首页>arguments......

arguments......

2022-06-11 06:28:00 Saucey_ six

Let's start with a piece of code :

function diTui(n) {
    if(n===1){
        return n
    }
    return diTui(n-1)*n
}
var test=diTui;
test=undefined; 
test(5);

ask , Can this code be executed effectively ?
answer : Can not be , stay diTui To be an assignment undefined When , It has already failed

It's actually incorrect Of , The point of his investigation is not here
Let's look at another piece of code :

function diGui(n) {
    if(n===1){
        return n
    }
    return arguments.callee(n-1)*n
}
var test=diGui;
test(5);

This code will work properly
It's obvious , We used in recursion args A property of ,args.callee Instead of pointing to the anonymous function being executed .

arguments

1.arguments Is not an array , But with arrays length And index element attributes
2.arguments Convert to an array var args=Array.prototype.slice.apply(str,arguments)
3.arguments Defined callee and caller attribute .
4. all ( Except arrow function ) A local variable of a function , have access to args The object references a function's arguments in a function .
5.arguments It's an object .

arguments.callee( Points to the currently executing function )

  1. Used in anonymous recursive functions , Decoupling between function names and functions can be realized , After modifying the function name , Function internals can remain unchanged .
function jieChen(){
    return function(n){
        if(n<=1) return 1
        return n*arguments.callee(n-1)
    }
}
  1. Alternative , because args.callee It costs a lot to use
function jieChen(n){
    if(n<=1) return 1;
    let result=1;
    return (function fn(){
        result*=n
        n--;
        if(n!=0){
            fn()
        }
        return result
    })()
}

There is an interview question :

Accept parameters , Loop out array 【1,2,3,4,5】, Out of commission for loop .

function show(n){
    let result=[]
    return (function () {
        result.unshift(n)
        n--
        if(n!=0){
            arguments.callee();
        }
        return result
      })()
}

arguments.caller( Points to the function that calls the current function )

function whoCalled() {
   if (arguments.caller == null)
      console.log(' This function is called in the global scope .');
   else
      console.log(arguments.caller + ' Called me !');
}
原网站

版权声明
本文为[Saucey_ six]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110623221088.html