如何在其他函数中使用fn作为函数参数

How can i use fn as function parameter in other function?

本文关键字:函数 fn 参数 其他      更新时间:2023-12-15

如何在其他函数中使用fn作为函数参数?此外,fn参数具有自参数。比如test("b('aa')"),怎么办?

JAVASCRIPT

<script type="text/javascript">
    function test(fn){
        if(fn){
            fn();
        }
    }
    function a(){
        alert(1);
    }
    function b(x){
        alert(x);
    }
    /* 
        when click I get errors => TypeError: fn is not a function
    */
</script>

HTML

 <button onclick="test('a')">test('a')</button>
    <button onclick="test('b(hello)')">test('b(hello)')</button>

因为'a'IS是真的,但它不是函数。这应该有效:

<button onclick="test(a))">test('a')</button>

此外,你在测试中的条件不应该是if(fn){,它应该是:

if(typeof fn === 'function'){

你可以用这种方式执行b:

<button onclick="test(b.bind(null, 'hello'))">test('b(hello)')</button>

这将把b函数传递给test,"hello"绑定作为其第一个参数

只需编写以下内容。

<script type="text/javascript">
    function test(fn,parameter){
        if(fn){
            fn.apply(window,parameter||[]);
        }
    }
    function a(){
        alert(1);
    }
    function b(x){
        alert(x);
    }
    /* 
        when click I get errors => TypeError: fn is not a function
    */
</script>
<button onclick="test(a)">test('a')</button>
<button onclick="test(b,['hello'])">test('b(hello)')</button>

感谢Felix Kling的评论。这是解释。

NOT正确,因为"b(hello)"是一个字符串对象。

test('b("hello")')

NOTcorrect,因为您得到的实际上是b('hello')的返回值,它是未定义的。

test(b('hello'))

要将参数发送到功能测试,必须将fn和参数分开。

您可以使用Function.protype.apply(thisValueargumentsList)。

正如我所写的,

fn.apply(window,parameter||[])

fn函数的this值默认为window。

parameter是参数列表,它位于<button>test('b(hello)')</button>元素中的['hello']。||[]防止未定义的变量。test(a)是一个没有实现参数的示例。

使用jQuery,您可以在不需要更改函数的情况下代理参数:

<button onclick="test(a)" />
<button onclick="test($.proxy(b,window,'hello')" />

或者在功能范围内,你可以测试b的artiy

if (x.arity>0){
  x(arguments[1])
}

并通过test(b,'hello'); 点击