我正在回顾 Backbone 待办事项列表,并对集合有疑问。
这是代码:
window.TodoList = Bacbone.Collection.extend({
model: Todo,
localStorage: new Store("todos"),
done: function() {
return this.filter(function(todo){return todo.get("done")})
},
remaining: function() {
return this.without.apply(this, this.done());
}
})
我了解这里发生的一切,除了“剩余”功能。
return 语句:return this.without.apply(this, this.done());
使用下划线方法的代理 - _.without
根据 Underscore 文档,其用途如下:
without_.without(array, [*values]) Returns a copy of the array with all instances of the values removed. === is used for the equality test.
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); => [2, 3, 4]
所以,我明白它是说返回集合中的所有内容,而不带值为“true”的“done”属性。
我不明白的是链接到它的“apply”函数。这不会出现在 Backbone 文档或 Underscore 文档中。至少我在任何地方都找不到它。
谁能详细解释一下 Return 语句中这些元素发生了什么?
最佳答案
this
指的是集合。
apply
是 JavaScript 函数的一种方法,允许您设置方法的上下文并将值数组发送给调用者。
apply
期望上下文作为第一个参数,然后是一个数组
或类似数组(例如参数
)它将作为参数传递给函数。
您可以使用 .call
执行相同的操作,但第二个以上参数以逗号分隔。
apply
和 call
是 JavaScript 原生的。
所以...
返回 this.without.apply(this, this.done());
方法 this.done()
返回一个数组,但使用集合的上下文,并通过 without
方法传入一系列要忽略的值。这又返回集合中未完成的所有待办事项。
示例:
_.without([1,2,3,4],1,2); === _.without.call([], [1,2,3,4], 1, 2);
关于javascript - Backbone.js - Todo Collection - 这个返回语句中到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9137398/