简体   繁体   English

如何从闭包调用javascript类函数

[英]How to call javascript class function from closure

I'm working on a jQuery plugin that does not have a selector. 我正在开发一个没有选择器的jQuery插件。 When initializing it, I instanciate an object that has functions. 初始化时,我实例化了一个具有功能的对象。 In these functions, I need to use closures. 在这些函数中,我需要使用闭包。 In these closures, I would like to call my initial object functions. 在这些闭包中,我想调用我的初始对象函数。

To make it more clear, here is a simplified version of the code. 为了更加清楚,这是代码的简化版本。

HTML 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 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);

The problem is that notify(this.html()); 问题是notify(this.html()); raises an error ReferenceError: notify is not defined 引发错误ReferenceError: notify is not defined

How can I reach this notify method? 我怎样才能达到这种通知方式?

You can assign this to a separate local variable in a closure. 您可以指定this在封闭独立的局部变量。 You need to do that because this will no longer point to your MyEditor object inside the each , it will point to each of the .editables 您需要执行this操作,因为this将不再指向each对象内部的MyEditor对象,而将指向每个.editables

Also, you probably meant to call this.notify() , since the function is attached to the prototype of MyEditor 另外,您可能想调用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