The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Structure of js code

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #151631

    Hi, everyone.

    I have read this interesting article and wrote simple application using this technic, but in comments everyone wrote about problem with global “s”, and as for me no one write understandable solution. Can somebody help me to find one. Appreciate your help. Thanks.


    Brendan’s comment sums up a very good solution.

    The problem they’re talking about is global scope: basically, naming conflicts. If you define someVar here, then you have to remember that you can’t use that variable name anywhere else, or you’d have a collision, and the first value would be lost – probably breaking things.

    In a more academic perspective, s is logically part of the newsWidget object, and so should be inside that object (rather than outside, in the global scope, where it might get smashed).

    By wrapping the whole thing in a self-executing function, you create a closure around s: it’s still available to the newswidget (me in Brendan’s example), but it can’t be reached from the global scope, or anywhere else.


    Thanks @traq, I uderstood. I found similar solution, but without ** me**:

    var NewsWidget = (function () {
        var s; // private alias to settings
        return {
            settings: {
                numArticles: 5,
                articleList: $("#article-list"),
                moreButton: $("#more-button")
            init: function() {
                s = this.settings;
            bindUIActions: function() {
                s.moreButton.on("click", function() {
            getMoreArticles: function(numToGet) {
                // $.ajax or something
                // using numToGet as param
Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.