1

在最后一行中,如何确保我所指的“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
}
4

1 回答 1

1

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

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

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

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

于 2012-10-28T22:00:46.083 回答