开发者

Global variables for nested object classes in jQuery

So i have the following structure in my js file:

var scrollingElements = {

    doc_height :    null,
    window_height : null,

    globalVar : {
        init: function() {
            //Get window and document initial heights
            this.doc_height     = $(document).height();
            this.window_height  = $(window).height();
        }
    },

    headerNav : 开发者_运维问答{
        init: function(){
            console.log(this.doc_height);
        }
    },

    quickNavSidebar : {
        init: function(){
            console.log(this.doc_height);
        }
    }

}

$(function(){
    scrollingElements.globalVar.init();
    scrollingElements.headerNav.init();
    scrollingElements.quickNavSidebar.init();
});

However, this code doesn't work. this.window_height doesn't reach the right level in the object class. I'm unsure how to get to the higher level in order to store and access the global variables. I think i need to do something like this.parent(), but obviously that doesn't work :/

Any ideas?


You can't use this inside the object to refer to the variables like you did. They are properties of the object and inside the object can be accessed directly. This works for me:

var scrollingElements = {

    doc_height :    null,
    window_height : null,

    globalVar : {
        init: function() {
            //Get window and document initial heights
            doc_height     = $(document).height();
            window_height  = $(window).height();
            console.log(doc_height);
        }
    },

    headerNav : {
        init: function(){
            console.log(doc_height);
        }
    },

    quickNavSidebar : {
        init: function(){
            console.log(doc_height);
        }
    }

}


You need to save a reference to the enclosing class. Try reading a little about Javascript closures

var scrollingElements = {

    doc_height :    null,
    window_height : null,
    that: this,

    globalVar : {
        init: function() {
            //Get window and document initial heights
            that.doc_height     = $(document).height();
            that.window_height  = $(window).height();
        }
    },

    headerNav : {
        init: function(){
            console.log(that.doc_height);
        }
    },

    quickNavSidebar : {
        init: function(){
            console.log(that.doc_height);
        }
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜