• js中的函数function


        js的function对象在调用过程中具有一个arguments的属性,它是由脚本解释器创建的(这也是arguments创建的唯一方式)。

    arguments属性能够看作是一个Array对象,它有length属性,能够通过序号訪问每个參数,并且通过argument的callee属性能够获取对正在运行的Function对象的引用。例如以下:

    function factorial(n){
      if(n<=n){
       return 1;
       }else{
          return n*arguments.callee(n-1);
       }
    }
    alert(factorial(5));

    上面使用了callee属性完毕了一个递归的算法。


    Function的还有一个属性是caller,它指向正在调用当前函数的父函数对象。

    利用callee和caller属性,能够非常easy实现对堆栈的遍历,如:

    function fool(v1){
       foo2(v1,v2,v3);
    }
    function foo2(v1,v2){
      foo3(v1,v2,v2*v2);
    }
    
    function foo3(v1,v2,v3){
      var foo=argument.callee;
      while(foo&&(foo!=window)){
      document.writeln('<br>调用參数:<br>','-------------------------------<br>');
      
       var args=foo.argument;argn=args.length;
       for(var 1=0;i<arg;i++){
       document.writeln('args[',i,']:',args[i],'<br>');
       }
      document.writeln('<br>');
      foo=foo.caller;
      }
    }
    foo(5);

    Function是js中一个非常特殊的对象,其特殊体如今他的多重身份上。如:

    //function作为类的声明和实现
    function ClassA(){
      this.prop1="prop1";
       this.prop2="prop2";
    }
    //function作为构造函数
    var obj=new CalssA();
    
    //输出true,function作为类引用
    alert(obj instanceof CalssA);

    Function能够声明普通函数。这和其它语言的概念是一样的,但Function还能够用于类的声明和实现,对象的构造函数以及类的引用。上面的代码中通过functionkeyword声明了ClassA类,并通过thiskeyword声明了两个属性prop1和prop2,然后在创建obj对象时,ClassA()由起到了对象构造函数的作用;最后代码中使用instanceofkeyword推断obj对象是否是ClassA类的实例,此时ClassA又起到了类引用的作用。




  • 相关阅读:
    LeetCode:Plus One
    LeetCode:Text Justification
    LeetCode:Sqrt(x)
    LeetCode:Climbing Stairs(编程之美2.9-斐波那契数列)
    LeetCode:Simplify Path
    LeetCode:Edit Distance
    LeetCode:Set Matrix Zeroes
    LeetCode:Search in Rotated Sorted Array I II
    LeetCode:Search a 2D Matrix
    LeetCode:Sort Colors
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/6867087.html
Copyright © 2020-2023  润新知