• js递归函数和call()


    1、递归函数

      如果一个函数在其主体中直接或间接调用其本身,则这样的函数则称为“递归函数”

    function myFun(n){
        if(n == 1){
            return 1;
        }       
        return n*myFun(n-1);    
    }
    alert("5的阶乘为:"+myFun(5));

    2、call()方法和apply()方法

      Function对象的call()方法和apply()方法可以实现像调用对象的方法一样调用函数。

      call和apply是为了动态改变this而出现的,当一个object没有某个方法,但其他的有,可以借助call或apply用其他对象的方法来操作

      call与apply的不同就是call传的值可以是任意的,而apply传的值必须为数组

      常用实例:

    function add(a,b){
       alert(a+b);   
    }
    function sub(a,b){
       alert(a-b);
    }
    add.call(sub,3,1);
    /*用add来替换sub
    add.call(sub,3,1) == add(3,1)
    所以运行结果为:alert(4)*/
        function Animal(){    
            this.name = "Animal";    
            this.showName = function(){    
                alert(this.name);    
            }    
        }    
          
        function Cat(){    
            this.name = "Cat";    
        }    
           
        var animal = new Animal();    
        var cat = new Cat();    
            
        //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。    
        //输入结果为"Cat"    
        animal.showName.call(cat,",");    
        //animal.showName.apply(cat,[]);  

    实现继承

        function Animal(name){      
            this.name = name;      
            this.showName = function(){      
                alert(this.name);      
            }      
        }      
            
        function Cat(name){    
            Animal.call(this, name);    
        }      
            
        var cat = new Cat("Black Cat");     
        cat.showName();  

    多重继承

        function Class10()  
        {  
            this.showSub = function(a,b)  
            {  
                alert(a-b);  
            }  
        }  
          
        function Class11()  
        {  
            this.showAdd = function(a,b)  
            {  
                alert(a+b);  
            }  
        }  
          
        function Class2()  
        {  
            Class10.call(this);  
            Class11.call(this);  
        }  
  • 相关阅读:
    tarjan无向图缩点
    8、11 T1:入阵曲:复杂度估算,观察规律与性质,数据存储与查询
    容斥系数
    模拟测试12:
    模拟测试11:冷静稳健。
    好的文章
    容器,函数等
    后缀数组:
    HDU5618 Jam's problem again CDQ分治
    P3810 陌上花开 CDQ分治
  • 原文地址:https://www.cnblogs.com/ywang/p/5942571.html
Copyright © 2020-2023  润新知