1

我很难理解剩余函数在下面的代码中是如何工作的。

(注释来源:http ://documentcloud.github.com/backbone/docs/todos.html )

我对 apply 的理解是第一个参数是上下文,其余参数是一个数组,作为参数传递给正在应用的函数。

var TodoList = Backbone.Collection.extend({
      model: Todo,
      localStorage: new Backbone.LocalStorage("todos-backbone"),
      done: function()
      {
        return this.filter(function(todo) { return todo.get('done'); });
      },
      remaining: function() 
      {
        return this.without.apply(this, this.done());
      },
});

所以:

this.without.apply(this, this.done()); --> 翻译为:

without(array of arguments as parameters to without function);

without 将第一个参数作为数组和要从数组中删除的 2...n 个参数。

我不明白这个功能是如何做任何有用的事情的。对我所缺少的东西的解释会有所帮助。

4

2 回答 2

0

Backbone:混合每个 Underscore 方法作为 Collection#models 的代理

_.each(methods, function(method) {
    Collection.prototype[method] = function() {
      //convert arguments to array. Such as: args = [1, 2, 3]
      var args = slice.call(arguments);
      //add this.models at the begining of array. Such as: [['string'], 1, 2]
      args.unshift(this.models);
      //_[without].apply(_, [['string'], 1, 2])
      //_.without(['string'], 1, 2);
      return _[method].apply(_, args);
    };
  });
于 2013-03-20T06:26:05.580 回答
0

this.without.apply(this, this.done()); --> 翻译为:without(array);

并不真地。您知道的将数组作为第一个参数的下划线函数可以用作骨干集合上的方法(如下划线链接包装器)。让我们假设this.done()计算结果为[x, y, z],然后apply调用转换为

this.without(x, y, z);

当然,更高效的方法是

return this.filter(function(todo) { return ! todo.get('done'); });
//                                         ^
于 2013-03-06T13:43:02.233 回答