为什么jQuery document.ready在自调用JavaScript函数中调用在不同范围函数中定义的函数?

时间:2015-09-13 00:53:47

标签: javascript jquery

我有两个不同的函数,它们的值是自我调用的。在每个函数中,我都有一个“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 "

这是为什么?有没有办法避免这种情况?

3 个答案:

答案 0 :(得分:3)

你真的不需要做任何这些,你应该能够直接将函数发送到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 objecthttps://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');
    }
};

但是,你真的不需要包装它。我只是在这里解释你想要做什么。

答案 1 :(得分:2)

这似乎有效:

var LightBox = (function(){

    $(document).ready(function(){ init(); });

    var init = function(){
        console.log('Lightbox Init');
    };
})();

var CustomAnchors = (function(){

    $(document).ready(function(){ init(); });

    var init = function(){
        console.log('CustomAnchors Init');
    };
})();

示例中this的值不是您期望的函数对象。

答案 2 :(得分:1)

尝试从LightBoxCustomAnchors返回功能;在IIFE之外使用.ready()变量LightBoxCustomAnchors作为数组中的函数,由.ready()调用



var LightBox = (function(){
        
    return function(){
        console.log('Lightbox Init');
    }

})();

var CustomAnchors = (function(){
    
    return function(){
        console.log('CustomAnchors Init');
    }
    
})();

$(document).ready([LightBox, CustomAnchors])

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
&#13;
&#13;
&#13;

相关问题