javascript - 如何从闭包中调用javascript类函数

标签 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

我怎样才能到达这个通知方法?

最佳答案

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

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

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());
    });
};

关于javascript - 如何从闭包中调用javascript类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27800580/

相关文章:

Lua 表从 API 到主程序不可见

actionscript-3 - as3奇怪的堆栈溢出发生

c# - 在 webbrowser c# 控件中停止警报 javascript 弹出窗口

javascript - 无法在服务器端注销用户(Next.js 和 Supabase)

python - python如何在调用嵌套函数时记住封闭范围变量的值?

javascript - 如何获得正确形式的 JavaScript 和 Ruby 时间戳?

在运行时添加的 <a> 标签的 Jquery Click 事件不会被触发

javascript - 您如何使用 javascript 在 FF 中切换 div 的可见性? (IE 和 Chrome 工作正常)

javascript - 将状态从 App.js 传递到 React Router 组件

用于输入文件按钮的 Javascript,以通知文件上传完成