JS中回调函数的方法

How to callback a function in JS

我正在为 Froala (https://www.froala.com/wysiwyg-editor) 构建自定义插件:

// Custom plugin
(function(FroalaEditor) {
  // Add an option for your plugin.
  FroalaEditor.DEFAULTS = Object.assign(FroalaEditor.DEFAULTS, {
     myOption: false
  });

  // Define the plugin.
  // The editor parameter is the current instance.
  FroalaEditor.PLUGINS.myPlugin = function(editor) {
    // Private variable visible only inside the plugin scope.
    var private_var = "My awesome plugin";

    // Private method that is visible only inside plugin scope.
    function _privateMethod() {
      console.log(private_var);
    }

    // Public method that is visible in the instance scope.
    function publicMethod() {
      console.log(_privateMethod());
    }

    // The start point for your plugin.
    function _init() {
      // You can access any option from documentation or your custom options.
      console.log(editor.opts.myOption);

      // Call any method from documentation.
      // editor.methodName(params);

      // You can listen to any event from documentation.
      // editor.events.add('contentChanged', function (params) {});
    }

    // Expose public methods. If _init is not public then the plugin won't be initialized.
    // Public method can be accessed through the editor API:
    // editor.myPlugin.publicMethod();
    return {
      _init: _init,
      publicMethod: publicMethod
    };
  };
})(FroalaEditor);

然后我有一个带有回调的按钮插件,我想从中调用插件:

  FroalaEditor.DefineIcon('alert', {NAME: 'info', SVG_KEY: 'help'});
  FroalaEditor.RegisterCommand('alert', {
    title: 'Hello',
    focus: false,
    undo: false,
    refreshAfterCallback: false,
    callback: function () {
      this.myPlugin();
    }
  });

但是我得到了错误:this.myPlugin is not a function

我哪里错了?

Javascript 中的 this 关键字在回调中使用时很容易发生变化。绑定您的函数,使 this 锁定到当前作用域,或者使用作用域中的另一个变量来跟踪它。

function myCallback() {
    console.log(this.something);
}
let safeCallback = myCallback.bind(this);

let that = this;
function myCallback() {
    console.log(that.something);
}