【问题标题】:How can I pass a variable into a lambda function? Dynamic Lambda functions如何将变量传递给 lambda 函数?动态 Lambda 函数
【发布时间】:2012-10-28 21:48:56
【问题描述】:

在最后一行中,如何确保我所指的“this”是实例化的 k8rModal 对象,而不是运行函数的对象?

对于未来的其他项目,我还需要动态构造 lambda 函数。如果没有全局变量,这可能吗?

function k8rModal(DOMnamespace){
    var _ = this._ = DOMnamespace+"_"; // for DOM namespacing

    this.tightWrap=1;

    $('body').prepend('<div id="'+_+'stage"></div>');
    this.stage = stage = $('#'+_+'stage');
    stage.css({
        'display':'none',
        'width':'100%',
        'height':'100%',
        'color':'#333'
    });

    $('body').append('<div id="'+_+'slate"></div>');
    this.slate = slate = $('#'+_+'slate');
    slate.css({
        'display':'none',
        'width':'640px',
        'height':'480px',
        'color':'#eee'
    });

    $('body').delegate('.'+_+'caller','click',function(){
        /* this... but not, this? */.appear();
    });
}

k8rModal.prototype.appear = function(){
    //make the modal box appear
}

【问题讨论】:

  • 不要到处使用this,只需在函数顶部使用var that = this;,然后再使用that。那么在其他范围内,他们仍然可以使用自己的this,但仍然将更高的this 引用为that

标签: javascript javascript-objects lambda oop


【解决方案1】:

虽然您可以按照@ianpgall 的建议使用变量引用来引用正确的对象,但另一种可能性是为此目的使用 jQuery 的事件数据。

$('body').delegate('.'+_+'caller','click', {k8r: this}, function(event){
    event.data.k8r.appear();
});

或者,如果您使用的是 jQuery 1.7 或更高版本,您可能应该改用 .on()。j

$('body').on('click', '.'+_+'caller', {k8r: this}, function(event){
    event.data.k8r.appear();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多