如何检查注入函数的参数?

时间:2016-03-10 17:51:10

标签: javascript dependency-injection

接受函数 fB 的函数 fA 如何作为参数验证 fB' 所需的参数?

var some_object = { fA : function( fB )
                           { 
                             // This function will send one parameter, a string, into fB ...
                             //   ... no matter how fB is designed.
                             // Therefore a mechanism is needed to check fB's arguments.

                             console.log( "Aa : " + fB            ) ;       
                             console.log( "Ab : " + fB.arguments  ) ;          
                             console.log( "Ac : " + fB.toString() ) ;         
                             console.log( "Ad : " + typeof fB     ) ;         


                             var lva_args = fB.toString().split(")")[0].split("(")[1].trim().split(/\s*,\s*/)                             ;

                             console.log( "Ae : " + lva_args)  ; 
                             // argn,arga,args .... 
                             //   ... but these are just their names, 
                             //       and do NOT indicate their type  

                             console.log( "Af : " + typeof lva_args[ 0 ] + " , " + typeof lva_args[ 1 ] + " , " + typeof lva_args[ 2 ]   ) ; 
                             // string , string , string 

                             var processed = fB.apply( null , [ 'abc' ] ) ;
                             return processed ;
                           }
                  } ;

var the_result = some_object.fA( function my_any_function( argn  , arga , args )  
                                   { console.log( "Ba : " + typeof argn + " , " + typeof arga + " , " + typeof args ) ; 
                                     // string , undefined , undefined 

                                     return argn * 10  ; 
                                     // argn should be a number !!!
                                     // .fA()  and  my_any_function 
                                     //    ... are NOT in agreement
                                   }
                                ) ;   

console.log( "Z : " +  the_result ) ; // --> NaN ... but it could've been worse.

我包含了`.toString()'选项,因为我理解角度转换将函数注入到字符串中,然后通过它们解析查找参数,但这一定非常混乱(感谢@georgeawg)。

我的plunker

1 个答案:

答案 0 :(得分:0)

我认为你在问题中提到的Angular方法(解析函数的字符串表示)是测试 fB 参数的唯一方法。仅供参考,here's the source for how Angular does this parsing

但是,在您的情况下,即使这种方法也不能保证 fB 接受您期望的参数 - 这种方法可能会产生漏报。例如,根据其签名,此函数不带参数:



function functionWithNoArguments() {
  document.writeln(arguments[0]);
}

functionWithNoArguments('Hello, world!');




另请参阅:How to get function parameter names/values dynamically from javascript