2013-04-05 52 views
0

我試圖將「term」傳遞給外部函數。如何自動將jQuery函數參數傳遞給外部函數?

$('#item').terminal(function(command, term) { 

我一直能夠做到這一點的唯一方法是通過在函數中傳遞「term」。

myfucntion(term, 'hello world'); 

有沒有一種方法,我可以做到這一點,而不必每次都通過它?

編輯:

$(function() { 
    $('#cmd').terminal(function (command, term) { 
     switch (command) { 
      case 'start': 
       cmdtxt(term, 'hello world'); 
       break; 

      default: 
       term.echo(''); 
     } 
    }, { 
     height: 200, 
     prompt: '@MQ: ' 
    }); 
}); 

function cmdtxt(term, t) { 
    term.echo(t); 
} 
+1

我不清楚你在做什麼。請提供更完整的示例。 – 2013-04-05 12:57:03

+0

我加了我的完整代碼。正如你所看到的,我將外部函數傳遞給外部函數,可以稱之爲回聲函數。 – Shylor 2013-04-05 13:02:02

回答

0

是的,你可以把它從全球到兩種功能。

var my_store = { 
    term: // what ever is term probably function(){.....} 
}; 
$(function() { 
    $('#cmd').terminal(function (command, term) { 
     switch (command) { 
      case 'start': 
       cmdtxt('hello world'); 
       break; 

      default: 
       term.echo(''); 
     } 
    }, { 
     height: 200, 
     prompt: '@MQ: ' 
    }); 
}); 

function cmdtxt(t) { 
    my_store.term.echo(t); 
} 

我把它放在my_store的原因是對污染的全球空間儘可能少。所以它的作用是存儲在全局範圍內訪問的變量。

1

你可以放置的cmdtxt聲明匿名terminal回調中:

$('#cmd').terminal(function (command, term) { 

    // ** define cmdtxt using the in-scope `term` ** 
    function cmdtxt(t) { 
     term.echo(t); 
    } 

    //... 

    cmdtxt('hello world'); 

    //... 

    } 
}, { height: 200, prompt: '@MQ: ' }); 

通過定義的回調函數內的cmdtxt功能,您將termcmdtxt範圍內。這是因爲termcmdtxt定義時在範圍內,並且JavaScript允許函數訪問函數定義時在範圍內的所有變量。 (在計算機科學方面,我們說,在範圍變量包括內部的新function closure詞法範圍)。但是

注意的是,這種變化將使cmdtxt無法訪問該回調函數之外。如果你確實需要其他地方的cmdtxt函數,你總是可以在你需要的範圍內重新定義它。