While reading Hashrocket's blog on tilemapping, I learned about a new way of organizing code.

The way I'm used to is:

(function start () {
   scene();
})();

function scene() {
   renderLayer();
}

function renderLayer() {
   var x
   var y
}

etc...

Hashrocket creates an object within a function wrapper and adds functions and variables as attributes to the object:

$(function() {
    var scene = {
      layers: [],
      renderLayer: function(layer) { },
      renderLayers: function(layers) { },
      loadTileset: function(json) { },
      load: function(name) { }
    }

scene.load(something);

});

What is the name and what are the differences/benefits of this style of coding? It seems OOP-like, as scene = { would be the class, and its properties would be the methods/attr within the class.

Thanks!

有帮助吗?

解决方案

The main advantage of storing your functions in an object is reducing the odds of a name clash. Your first example pollutes the global namespace with scene() and renderLayer() which is potentially dangerous if you have a moderate code base that includes other packages and modules.

In the second snippet, scene is defined inside a anonymous function. This provides two benefits:

  • It makes the scene object inaccessible to code outside the function. Information hiding is enforced.
  • The evaluation of the declarations is deferred until the page has completely loaded all content (including images, script files, CSS files, etc.). This guarantees all resources will be available.

其他提示

For one thing, enclosing all your code within the anonymous function is better practice, since you're not polluting the namespace with functions. For another, the second example is better organized, since you know exactly what data/functions belong together.

It's not OOP, however, since you're not creating new instances of Scene.

Former example is an IIFE whereas latter one is just wrapping all the code(methods and state of object) that should belong together in the given JS object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top