簡體   English   中英

如何從閉包調用javascript類函數

[英]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操作,因為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());
});
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM