简体   繁体   中英

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

How can i use fn as function parameter in other function? and further more, the fn parameter has self parameter. such as test("b('aa')") , how to do?

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>

Because 'a' IS truthy, but it is not a function. This should work:

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

Also, your condition in test shouldn't be if(fn){ , it should be:

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

You could execute the b in this manner:

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

This would pass the b function to test with 'hello' bound as its first parameter

Simply write this.

<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>

Thanks for Felix Kling comment. Here is the explanation.

NOT correct, because 'b(hello)' is a string object.

test('b("hello")')

NOT correct, because what you get is actually the return value of b('hello'), which is undefined.

test(b('hello'))

To send the parameter to function test, you must separate the fn and the parameter.

You can use Function.prototype.apply( thisValue , argumentsList ).

As what I've written,

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

The this value of fn function is window as default.

parameter is the arguments list which is ['hello'] in your <button>test('b(hello)')</button> element. ||[] prevent undefined variable. test(a) is the example that has no argument implemented.

Using jQuery you can proxy arguments without need to change the functions:

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

Or within the function you can test for b's artiy

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

and click by test(b,'hello');

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