我有两个不同的函数,它们的值是 self 调用的。在每个函数中我都有一个“init”方法。如果我使用 document.ready 在两个函数中触发“init()” - 它们都只触发最后一个“init”,而不是它们自己的(因此它在 my example on jsFiddle 中被调用两次)。
var LightBox = (function(){
var me = this;
$(document).ready(function(){ me.init(); });
me.init = function(){
console.log('Lightbox Init');
}
})();
var CustomAnchors = (function(){
var me = this;
$(document).ready(function(){ me.init(); });
me.init = function(){
console.log('CustomAnchors Init');
}
})();
此代码的结果会记录“CustomAnchors Init”两次,但我希望它会记录“Lightbox Init”,然后是“CustomAnchors Init” >”
这是为什么呢?有没有办法避免这种情况?
最佳答案
您实际上不需要执行任何操作,您应该能够直接将函数发送到 document.ready
。您根本不需要将其包装在该匿名函数中:
var LightBox = (function() {
var init = function(){
console.log('Lightbox Init');
}
$(document).ready(init);
})();
var CustomAnchors = (function(){
var init = function(){
console.log('CustomAnchors Init');
}
$(document).ready(init);
})();
对您尝试执行的操作的解释:
正如其他人已经说过的,自从 Lightbox
只是一个直接函数(即使它是一个 IIFE),引用 this
它里面只会引用 global object
。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
您想要做的是引用this
作为自定义对象,但要使其工作,您必须实例化一个对象。执行此操作的一种方法是使用 new
运算符,如new Lightbox()
(如果 Lightbox
是一个函数)或 new function()
如果您只想从匿名函数创建一个实例。
使用您的特定代码,它将是
var LightBox = new function() {
var me = this; // this will now refer to the instantly instantiated LightBox object
$(document).ready(function(){ me.init(); });
this.init = function(){ // You could use me.init here but I think it makes for harder-to-understand code
console.log('Lightbox Init');
}
};
var CustomAnchors = new function(){
var me = this; // and same here, for the CustomAnchors object
$(document).ready(function(){ me.init(); });
this.init = function(){
console.log('CustomAnchors Init');
}
};
但是,您实际上并不需要将其包装起来。我只是在这里解释你想要做什么。
关于javascript - 为什么自调用 JavaScript 函数内的 jQuery document.ready 会调用在不同作用域函数中定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32545279/