why is spine.js Module.init implemented like this?

296 Views Asked by At

as defined here:

Module.init is implemented like:

Module.init = Controller.init = Model.init = (a1, a2, a3, a4, a5) ->
  new this(a1, a2, a3, a4, a5)

why is it like this? why define 5 attributes and not use attrs... so attributes are not fixed to 5....

new this(attrs...)
2

There are 2 best solutions below

4
On BEST ANSWER

Maybe it's because the compiled JS is much smaller (Spine.js makes a lot of emphasis on low footprint).

Module.init = Controller.init = Model.init = (a1, a2, a3, a4, a5) ->
  new this(a1, a2, a3, a4, a5)

Compiles to:

Module.init = Controller.init = Model.init = function(a1, a2, a3, a4, a5) {
  return new this(a1, a2, a3, a4, a5);
};

While:

Module.init = Controller.init = Model.init = (args...) ->
  new this args...

Compiles to the much more convoluted:

var __slice = [].slice;

Module.init = Controller.init = Model.init = function() {
  var args;
  args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  return (function(func, args, ctor) {
    ctor.prototype = func.prototype;
    var child = new ctor, result = func.apply(child, args), t = typeof result;
    return t == "object" || t == "function" ? result || child : child;
  })(this, args, function(){});
};

This is because in JavaScript the new operator and apply cannot be used in conjunction :(

1
On

Either someone didn't know about splats, or they felt that it was cleaner to do it this way, or maybe they were thought it would be more performant to not use a bunch of extra logic to process the arguments object.