簡體   English   中英

如何在其他函數中將fn用作函數參數?

[英]How can i use fn as function parameter in other function?

如何在其他函數中將fn用作函數參數? 而且, fn參數具有self參數。 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” 真實的,但它不是函數。 這應該工作:

<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函數以“ hello”綁定作為其第一個參數進行test

簡單地寫這個。

<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評論。 這是解釋。

正確,因為'b(hello)'是一個字符串對象。

test('b("hello")')

正確,因為您得到的實際上是b('hello')的返回值,該值未定義。

test(b('hello'))

要將參數發送到功能測試,必須將fn和參數分開。

您可以使用Function.prototype.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的技巧

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

然后按test(b,'hello');單擊test(b,'hello');

暫無
暫無

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

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