Pass a JavaScript function as parameter

前端 未结 13 1474
星月不相逢
星月不相逢 2020-11-22 07:06

How do I pass a function as a parameter without the function executing in the \"parent\" function or using eval()? (Since I\'ve read that it\'s insecure.)

13条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 08:03

    You can use a JSON as well to store and send JS functions.

    Check the following:

    var myJSON = 
    {
        "myFunc1" : function (){
            alert("a");
        }, 
        "myFunc2" : function (functionParameter){
            functionParameter();
        }
    }
    
    
    
    function main(){
        myJSON.myFunc2(myJSON.myFunc1);
    }
    

    This will print 'a'.

    The following has the same effect with the above:

    var myFunc1 = function (){
        alert('a');
    }
    
    var myFunc2 = function (functionParameter){
        functionParameter();
    }
    
    function main(){
        myFunc2(myFunc1);
    }
    

    Which is also has the same effect with the following:

    function myFunc1(){
        alert('a');
    }
    
    
    function myFunc2 (functionParameter){
        functionParameter();
    }
    
    function main(){
        myFunc2(myFunc1);
    }
    

    And a object paradigm using Class as object prototype:

    function Class(){
        this.myFunc1 =  function(msg){
            alert(msg);
        }
    
        this.myFunc2 = function(callBackParameter){
            callBackParameter('message');
        }
    }
    
    
    function main(){    
        var myClass = new Class();  
        myClass.myFunc2(myClass.myFunc1);
    }
    

提交回复
热议问题