2013-04-05 51 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函数,你总是可以在你需要的范围内重新定义它。