search

Home  >  Q&A  >  body text

javascript - Is it good to use object literals to organize code?

var test = {
    globalVariable: 'abc',
    
    init: function () {
        this.method();
        this.method0();
    },
    
    method: function () {
        ……
    },
    
    method0: function () {
        ……
    }
};

Or

(function () {
    var globalVariable = 'abc';
    
    // init
    method();
    method0();
    
    function method() {
        ……
    }
    function method0() {
        ……
    }
})();

Which one of these two is better? The object method looks very clear, but there are many disadvantages in using it. For example, when looking for methods and variables, you have to put this in front of them. Will this increase unnecessary performance consumption?

Writing it as an object will facilitate expansion, etc. Because inheritance and polymorphism can be carried out in an object-oriented manner. If the program iteration encounters logic that is the same or similar to the logic in the object in the future, it will be much more convenient~

伊谢尔伦伊谢尔伦2751 days ago668

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-06-12 09:30:53

    Consider using ES6+Babel. Using classes can also provide better OO

    reply
    0
  • PHP中文网

    PHP中文网2017-06-12 09:30:53

    js has deviated far from the author's original intention. The mainstream keeps twisting it towards OO, and another niche school wants to train it into functional style. Back to the question, I can see that the questioner is leaning towards OO, so just follow the ES6 and ES7 routines to make it better, and there will be no difference in performance.

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-12 09:30:53

    To understand it simply, it doesn’t matter. In fact, if you don’t pollute the external environment, you can do it no matter what you do.
    One more thing, don’t let your friend who takes over your code hate you...

    reply
    0
  • Cancelreply