2012-11-09 64 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語言的魔力。它可以(類型)通過將函數分配給對象的屬性,然後用參數調用它來編寫。當然,它是通過語言來實現的,並沒有臨時價值。 –

相關問題