如何从闭包调用javascript类函数
我正在开发一个没有选择器的jQuery插件。初始化它时,我实例化一个具有函数的对象。在这些函数中,我需要使用闭包。在这些闭包中,我想调用我的初始对象函数 为了让它更清楚,这里是代码的简化版本 HTML如何从闭包调用javascript类函数,javascript,jquery,scope,closures,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 c
<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>
问题是notify(this.html())代码>引发错误引用错误:未定义通知
如何达到此notify方法?您可以将此
分配给闭包中的单独局部变量。您需要这样做,因为这个将不再指向每个中的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()
{
//做事
var that=this;//MyEditor.prototype.notify=function(message=''){
不是有效的JavaScript,您使用的是预处理器吗?这实际上正是OP所要问的。他无法访问原型上的notify,因此需要这个
,但由于他在一个闭包中,这个
需要分配给闭包之外的某个东西才能在里面访问。@Juhana这个
是不同的每个
中的不同上下文我已经回溯了两次(没有双关语的意思,真的),回溯,添加了更多的解释来回答。非常感谢你的帮助,这正是我所需要的!这和前面提到的一样
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());
});
};