【问题标题】:How to call javascript class function from closure如何从闭包中调用javascript类函数
【发布时间】:2015-03-04 05:36:06
【问题描述】:

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

如何使用此通知方法?

【问题讨论】:

  • MyEditor.prototype.notify = function(message = ''){ 不是有效的 JavaScript,您使用的是预处理器吗?

标签: javascript jquery scope closures


【解决方案1】:

您可以将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());
    });
};

【讨论】:

  • 这实际上正是 OP 所要求的。他无法到达原型上的通知,因此需要this,但由于他在闭包中,因此需要将this 分配给闭包外部的某个东西才能在其中访问它。
  • @Juhana thiseach 内部的不同上下文
  • 我已经回溯了两次(不是双关语,真的),支持,添加更多解释来回答。
  • 非常感谢您的帮助,这正是我所需要的!
【解决方案2】:
MyEditor.prototype.init = function()
{
// Do stuff
var self = this;
$('.editables').each(function() {
    $this = $(this);

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

【讨论】:

  • 这和Jimmy已经提到的一样
猜你喜欢
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
相关资源
最近更新 更多