在下面的代码中,我很难理解剩余的函数是如何工作的。
(注释来源: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个参数作为要从数组中删除的参数。
我不明白这个函数是如何做有用的事情的。对我遗漏的东西进行解释会有所帮助。
发布于 2013-03-06 13:43:02
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-20 06:26:06
Backbone:混合使用每种下划线方法作为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);
};
});
https://stackoverflow.com/questions/15248652
复制相似问题