如何从关闭调用javascript类函数

时间:2015-01-06 14:17:43

标签: javascript jquery scope closures

我正在开发一个没有选择器的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

如何联系此通知方法?

2 个答案:

答案 0 :(得分: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());
    });
};

答案 1 :(得分:0)

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

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