簡體   English   中英

了解Javascript中的匿名函數

[英]Understanding Anonymous Functions in Javascript

假設一個具有功能:

function doSomething(){
    attachEvent("click", function(){
         //there is a lot of code in this anonymous function
         //It may need to be defined somewhere else as a named function             
         doSomethingElse = variable;
    });
}

一個人如何在其他地方定義它並傳遞一個變量

function doSomething(){
     //this fires straight away 
     attachEvent("click", doNamedFunction(this.variable)); 
}

function doSomething(){
    //works but arguments aren't being passed
    attachEvent("click", doNamedFunction);
}

//I am defined as a named function instead of an anonymous function
function doNamedFunction(arg){
     doSomethingElse = arg;
     //do lots of other stuff below
}

所以問題是如何聲明命名函數並傳遞參數來代替匿名函數,還是您始終需要使用匿名函數作為回調。

提前謝謝了!

您必須將函數包裝在匿名函數中,或者使用在較新的瀏覽器中可用的.bind() API:

    attachEvent("click", doNamedFunction.bind(undefined, this.variable));

.bind()調用返回會調用“doNamedFunction”與函數undefinedthis值,你給出的參數。 除了一些(有趣的)細節之外,您還可以將.bind()視為為您創建匿名函數的機制。

暫無
暫無

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

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