Javascript modular design template - which is better: self-running function or object approach?

In my quest to write better, tougher, more secure code, I am very happy to accept a more modular template in my Javascript. However, in my self-education on this issue, I see that there are different ways to do this. It seems that the two most common would be self-starting function templates ( from this article ):

var HTMLChanger = (function() {
  var contents = 'contents'

  var changeHTML = function() {
    var element = document.getElementById('attribute-to-change');
    element.innerHTML = contents;
  }

  return {
    callChangeHTML: function() {
      changeHTML();
      console.log(contents);
    }
  };

})();

HTMLChanger.callChangeHTML();       // Outputs: 'contents'
console.log(HTMLChanger.contents);  // undefined

or from this other article , the object approach template:

var s,
NewsWidget = {

  settings: {
    numArticles: 5,
    articleList: $("#article-list"),
    moreButton: $("#more-button")
  },

  init: function() {
    s = this.settings;
    this.bindUIActions();
  },

  bindUIActions: function() {
    s.moreButton.on("click", function() {
      NewsWidget.getMoreArticles(s.numArticles);
    });
  },

  getMoreArticles: function(numToGet) {
    // $.ajax or something
    // using numToGet as param
  }

};

And I'm sure that many others (some of which are described in the first article) - which template is better and / or more general? If I were to choose the default option (unless I had a specific reason to choose a different template), and this should be and why?

?

+4
1

, , , , , .

, . , .

( SEAF IIFE) , , , . , return.

, JavaScript, - # Bad JavaScript Habits. , # Javascript, , JS.

, IIFE , , , , . , . , IIFE, , : -)

+4

Source: https://habr.com/ru/post/1651191/


All Articles