Baseline and javascript sample application

Hi, can someone explain why in the application of the baseline example ( http://backbonejs.org/examples/todos/index.html ) the function Remained () is (this.without.apply (this, this.done ( ));), not 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()); }, 

Thanks!

auto update

Debug output

 this.without(this.done()) [child, child, child, child] this.without.apply(this, this.done()); [child, child, child] 
+6
source share
3 answers

Variable argument list

The key in the way without is written:

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

It expects a variable argument list, and one way to do this is to apply:

 ... return this.without.apply(this, ['pass', 'these', 'arguments']); 

There's more about the application in the MDN documentation .

+4
source

You asked what is the difference between these two calls:

 this.without( this.done() ) 

vs.

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

To clarify, remove the nested call to this.done() . Now the first one:

 var value = this.done(); this.without( value ); 

This code explicitly calls this.without() and passes it one argument, regardless of the value returned by this.done() . If value turns out to be an array, the entire array is passed as one argument.

Second version:

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

This calls this.without() with a variable number of arguments, one argument for each array element. (And I called it array instead of value this time, because it makes sense for this code, it must be an array.)

.apply() also sets this in the called function, so passing this because the first argument just passes this along with this function is the same as a regular call to this.without() .

+2
source

apply also allows you to specify the "this" object for the function. Sometimes it matters, for example, when it is called in closure, where "this" may differ from your intention.

0
source

Source: https://habr.com/ru/post/949857/


All Articles