如何从关闭调用javascript类函数

Réj*_*ôme 2 javascript jquery closures scope

我正在研究一个没有选择器的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>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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

如何获得此通知方法?

小智 6

您可以this在闭包中分配单独的局部变量.你需要这样做因为this不再指向你MyEditor内部的对象each,它会指向每一个.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());
    });
};
Run Code Online (Sandbox Code Playgroud)