javascript - 合并这个内部回调

标签 javascript node.js

我在 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/

相关文章:

node.js - 后续迁移

javascript - 无法使引用 header 正常工作

node.js - Enide Studio 2014无法使用

node.js - 使用 node.js 的 Docker 开发工作流程

javascript - 如何选择给定条件的数据

javascript - 如何在 JavaScript 中创建双向映射,或以其他方式交换值?

javascript - Ember.js - 列出商店中的值

javascript - 如何将参数传递给 MEAN.js 包的express.js 服务器端路由。

javascript - 如何在不破坏文本内容本身的情况下将 CSS 应用于某些文本的一部分

javascript - 覆盖 Firefox 和 Chrome 中的快捷键