如何从闭包中调用 javascript class 函数

How to call javascript class function from closure

我正在开发一个没有选择器的 jQuery 插件。初始化它时,我实例化了一个具有功能的对象。在这些函数中,我需要使用闭包。在这些闭包中,我想调用我的初始对象函数。

为了更清楚,这里是代码的简化版本。

HTML

<script src="/path/to/jquery/2.1.1/jquery.min.js"></script>
<script src="/path/to/my/script/myeditor.js"></script>

<div class="editable">Div1</div>
<div class="editable">Div2</div>

<script>
    $.myeditor({
        option1: 'a',
        option2: 'b'
    });
</script>

myeditor.js

function ($) {

var MyEditor = function (options)
{
    this.$options = $.extend(true, {}, $.myeditor.defaults, options);
    this.init();
};

$.myeditor = function (options = {})
{
    return new MyEditor(options);
};

$.flyeditor.defaults = {
    option1: '1',
    option2: '2'
};

MyEditor.prototype.notify = function(message = '')
{
    console.log(message);
};

MyEditor.prototype.init = function()
{
    // Do stuff
    $('.editables').each(function() {
        $this = $(this);

        // Here comes the error
        notify($this.html());
    });
};

}(jQuery);

问题是 notify(this.html()); 引发错误 ReferenceError: notify is not defined

如何到达这个通知方法?

您可以将 this 分配给闭包中的单独局部变量。您需要这样做,因为 this 将不再指向 each 中的 MyEditor 对象,它将指向每个 .editables

此外,您可能打算调用 this.notify(),因为该函数附加到 MyEditor

的原型
MyEditor.prototype.init = function()
{
    // Do stuff
    var that = this; // <-- now we can reach this inside function.
    $('.editables').each(function() {
        $this = $(this);

        // Here comes the error
        // You can't use notify, that function is not defined
        // You can't use this.notify because this points to something else (the node)
        // inside the function in each
        that.notify($this.html());
    });
};
MyEditor.prototype.init = function()
{
// Do stuff
var self = this;
$('.editables').each(function() {
    $this = $(this);

    // Here comes the error
    self.notify($this.html());
});
};