【发布时间】: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