如何自动将jQuery函数参数传递给外部函数?

时间:2013-04-05 12:55:57

标签: jquery

我试图将“term”传递给外部函数。

$('#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);
}

2 个答案:

答案 0 :(得分: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函数,可以将term放在cmdtxt的范围内。这是因为termcmdtxt定义时是范围内的,并且JavaScript允许函数访问函数定义时范围内的所有变量。 (在计算机科学术语中,我们说范围内的变量包含在新function closure词法范围中。)

但请注意,此更改将使cmdtxt在该回调函数之外无法访问。如果您确实需要其他地方的cmdtxt功能,您可以随时在任何需要的范围内重新定义它。

答案 1 :(得分: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中的原因是为了尽可能少地污染全球空间。因此,它的作用是存储在全局范围内访问的变量。