我正在 js 中构建一个类,我使用 jQuery.on()
做一些事情。我知道我可以使用bind
制作类的范围引用this
,但这样它会替换 .on()
内当前对象的范围功能。我正在使用 var self = this
的老把戏,并且它有效,但我想知道是否有更优雅的方法来做到这一点。
这是我正在做的事情的示例:
var MyClass = function(settings){
this.mySetting = settings.mySetting;
this.otherSetting = settings.otherSetting;
this._initFunction();
};
MyClass.prototype = {
mySetting : '',
otherSetting : '',
_initFunction: function(){
// keep a referente to the class scope
var self = this;
$('.selector').on( 'click', '.trigger', function(){
if( self.mySetting == 'something' && self.otherSetting = 'some other thing'){
// here, this is referred to '.trigger'
$( this ).slideUp();
}
});
}
}
但是,如果我这样做,代码将无法工作,因为范围问题:
var MyClass = function(settings){
this.mySetting = settings.mySetting;
this.otherSetting = settings.otherSetting;
this._initFunction();
};
MyClass.prototype = {
mySetting : '',
otherSetting : '',
_initFunction: function(){
$('.selector').on( 'click', '.trigger', function(){
if( this.mySetting == 'something' && this.otherSetting = 'some other thing'){
// here, this is referred to 'MyClass', so it won't work
$( this ).slideUp();
}
}.bind( this ) );
}
}
有关如何使其更加优雅、避免使用 var 的任何提示 self = this
?
最佳答案
一种方法是使用 bind
使 this
指向 MyClass 实例,并使用 event
对象获取 DOM 元素触发了该事件。
MyClass.prototype = {
mySetting : '',
otherSetting : '',
_initFunction: function(){
$('.selector').on( 'click', '.trigger', function (event){
if( this.mySetting == 'something' && this.otherSetting = 'some other thing'){
$( event.target ).slideUp();
}
}.bind( this ) );
}
}
关于javascript - jQuery .on 和多个范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056858/