use*_*316 2 javascript backbone.js underscore.js
之前从未见过.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();
Run Code Online (Sandbox Code Playgroud)
函数对象附带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'
Run Code Online (Sandbox Code Playgroud)
在这两种方法中,都将this指针作为第一个参数传递.在该call()方法中,之后按顺序传递所有后续参数,以便第二个参数成为myFunc的第一个参数.在该apply()方法中,您将额外的参数作为数组传递.
| 归档时间: |
|
| 查看次数: |
1900 次 |
| 最近记录: |