为什么spine.js Module.init是这样实现的?

时间:2012-05-17 13:25:35

标签: coffeescript spine.js

定义为here

Module.init实现如下:

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

为什么会这样?为什么定义5个属性而不使用attrs...,所以属性不固定为5 ....

new this(attrs...)

2 个答案:

答案 0 :(得分:2)

也许是因为编译的JS要小得多(Spine.js非常重视低占用空间)。

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

编译为:

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

虽然:

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

编译得更复杂:

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(){});
};

这是因为在JavaScript中,new运算符和apply不能同时使用:(

答案 1 :(得分:1)

有人不知道splats,或者他们认为这样做更干净,或者他们认为不使用一堆额外的逻辑来处理参数对象会更有效率。 / p>

相关问题