Backbone示例应用和JavaScript应用

6

大家好,有人可以解释一下为什么在backbone示例应用程序(http://backbonejs.org/examples/todos/index.html)中,在remaining()函数中使用apply调用 (this.without.apply(this, this.done());)而不是 this.without(this.done()) 吗?

 // Filter down the list of all todo items that are finished.
done: function() {
  return this.where({done: true});
},

// Filter down the list to only todo items that are still not finished.
remaining: function() {
  return this.without.apply(this, this.done());
},

感谢您! #更新 调试器输出
this.without(this.done())
[child, child, child, child]
this.without.apply(this, this.done());
[child, child, child]
3个回答

4

可变参数列表

关键在于如何书写 without:

function () {
  var args = slice.call(arguments);
  args.unshift(this.models);
  return _[method].apply(_, args);
}

它预计一个变量列表的参数,一种方法是使用apply:
...
return this.without.apply(this, ['pass', 'these', 'arguments']);

有关apply的更多信息,请查看MDN文档


2

您问的是这两个调用之间的区别:

this.without( this.done() )

this.without.apply( this, this.done() );

为了澄清,让我们移除嵌套的this.done()调用。现在第一个是:
var value = this.done();
this.without( value );

这段代码显然调用了this.without()方法并将一个参数传递给它,该参数是由this.done()方法返回的任意value。如果value恰好是一个数组,则整个数组将作为单个参数传递。

第二个版本变成了:

var array = this.done();
this.without.apply( this, array );

那会调用 this.without() 方法,并将参数的数量设置为数组 array 的元素数。 (这里我称其为 array 而不是 value,因为为了让这段代码有意义,它必须是一个数组。) .apply() 同样也会在被调用的函数中设置 this,所以将 this 作为第一个参数传递,就像普通的 this.without() 方法调用一样,只是将 this 传递给了该函数。

0

apply方法还允许您为函数指定“this”对象。有时这很重要,比如在闭包中调用它时,“this”可能与您预期的不同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接