What exactly does .apply do?

a 夏天 提交于 2019-12-10 10:33:39

问题


Never seen the .apply method before. Can someone explains to me what it does? This is taken from http://addyosmani.github.com/backbone-fundamentals/

var app = app || {}; 
var TodoList = Backbone.Collection.extend({
model: app.Todo,
localStorage: new Backbone.LocalStorage(’todos-backbone’),
completed: function() {
    return this.filter(function( todo ) {
        return todo.get(’completed’); 
    });
},
remaining: function() {
    return this.without.apply( this, this.completed() );
}, 
nextOrder: function() {
    if ( !this.length ) { 
        return 1;
    }
    return this.last().get(’order’) + 1; },
comparator: function( todo ) { 
    return todo.get(’order’);
} 
});
app.Todos = new TodoList();

回答1:


The function object comes with apply() and call() methods. They both effectively do the same thing, except slightly differently. What they do is allow you to define the this pointer inside of that function's scope. So for example, if you do:

function myFunc(param1, param2) { alert(this) }

var first = 'foo';
var second = 'bar';

myFunc.call('test', first, second); //alerts 'test'

myFunc.apply('test', [first, second]); //alerts 'test'

In both methods, you pass the this pointer as the first parameter. In the call() method, you pass all subsequent parameters in sequential order after that, such that the second argument becomes the first parameter of myFunc. In the apply() method, you pass the extra parameters in as an array.



来源:https://stackoverflow.com/questions/13317526/what-exactly-does-apply-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!