简体   繁体   中英

Javascript Function Passing in as parameter

I want to pass some lines of code as parameter.

        function t_1()
        {
            var t6 = '';
            ////
            t_2(d1,d2,d3)
        }

        function t_2(c1, c2, c3)
        {
            var t1 = 12;
            if( t1 >12 )
            {
                // some code here
            }

        }

    </script>

Here in function t_2(), if conditions is static. But can i pass from t_1(). Like, condition in t_2() depends on t6 value in t_1().

Can i pass if condition code or any dynamic variable from t1 that can be executed in t2?

You can create anonymous function and pass it as an argument.

function t1()
{
    var x = 17;
    var f = function(a) { return a > x; }; // value of x is captured here inside f
    //                           ^^^^^^ here is expression you can pass around
    t2(f);
}

function t2(f)
{
    var y = 4;
    if(f(x)) {  //  ->  if(f(4))  ->  if(4>17)
        ...
    }
}

eval() could be a possible solution. Eg.

function t_1(){
  var a=5, b=10;
  //make you statement a string, any type of statement can be made string
  var c = "a+b"; 
  t_2(a,b,c);

}

function t_2(a,b,c){
  var res = eval(c); // here c can be any js statements in String form
}

eval() should be used with high precaution as it can make our application vulnerable to hacking. It should be used very selectively in case where we are getting input from the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM