我在 JavaScript 中有 OOP 函数,我在其中使用带回调的库。
代码如下:
$('body').mCustomScrollbar({
theme: 'minimal',
callbacks: {
whileScrolling: function() {
console.log(this.mcs.draggerTop);
}
}
});
内部回调函数(whileScrolling)我有this.mcs(由库制作)。但我无权访问我的 OOP 函数变量。 如果我想访问它们,我必须这样做
whileScrolling: function() {
console.log(this.mcs.draggerTop);
}.bind(this);
如果我这样做,我就可以通过它访问所有内容。变量(在 OOP 函数上),但我丢失了旧 this 内部回调中的每个变量,因此我不再有 this.mcs.draggedTop。
有没有办法“合并”this-es(前一个+新的)?
最佳答案
将外部 this
的值分配给一个变量,并在回调中使用该变量:
var outerThis = this; // the outer this
$('body').mCustomScrollbar({
theme: 'minimal',
callbacks: {
whileScrolling: function() {
// here this is the inner this
// and outerThis is the outer this
console.log(this.mcs.draggerTop);
}
}
});
关于javascript - 合并这个内部回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47227744/