2012-11-09 66 views
1

以前从未见过.apply方法。有人可以向我解释它的作用吗?这是从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(); 
+3

看看这里:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply – Blender

+2

它可以让你改变'this'的上下文并且传递一个数组作为参数。 – elclanrs

回答

7

的函数对象来采取apply()call()方法。他们都有效地做同样的事情,除了略有不同。他们所做的是允许您在该函数的作用域内定义指针this。因此,举例来说,如果你这样做:

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' 

在这两种方法,你通过this指针作为第一个参数。在call()方法中,之后按顺序传递所有后续参数,以便第二个参数成为myFunc的第一个参数。在apply()方法中,将多余的参数作为数组传递。

+0

辉煌...非常感谢你 – user1074316

+0

虽然我有一个问题,因为我们通过“这个”作为第一个参数如何工作? – user1074316

+0

@ user1074316语言的魔力。它可以(类型)通过将函数分配给对象的属性,然后用参数调用它来编写。当然,它是通过语言来实现的,并没有临时价值。 –

相关问题