簡體   English   中英

Javascript函數作為參數傳入

[英]Javascript Function Passing in 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>

在函數 t_2() 中,如果條件是靜態的。 但是我可以從 t_1() 過去嗎? 例如,t_2() 中的條件取決於 t_1() 中的 t6 值。

我可以通過if條件代碼或從t1可以在T2中執行任何動態變量?

您可以創建匿名函數並將其作為參數傳遞。

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() 可能是一個可能的解決方案。 例如。

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() 應高度謹慎地使用,因為它會使我們的應用程序容易受到黑客攻擊。 在我們從用戶那里獲得輸入的情況下,應該非常有選擇地使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM