我對「this」關鍵字有一個體面的理解,但由於某種原因,它仍然讓我在這個特定的情況下絆倒。在bindEvents方法內部,當我將提交事件綁定到表單時,它會執行fetchTweets。我明白現在它已經在「on」方法的回調函數中,因此「this」現在指的是事件綁定的表單,而不是父對象「Tweets」。「this」關鍵字在javascript回調函數中
我的理解是,通常的做法是在方法的頂部聲明self = this以緩存父對象,以防止稍後發生回調問題,但在這種情況下,它不起作用,因爲唯一目的是該方法將成爲表單提交事件的回調函數。
我知道.call和.apply,甚至$ .proxy,我只是想知道在這種情況下是否需要使用它們,或者如果我錯過了明顯的東西。我有這個代碼使用$ .proxy工作,我只是認爲可能有一個更智能的方法去實現它。
var Tweets = {
init: function (config) {
var self = this;
self.config = config;
self.url = 'http://search.twitter.com/search.json?callback=?';
self.bindEvents();
},
bindEvents: function() {
var self = this;
// bind events as needed
self.config.form.on('submit', self.fetchTweets);
},
fetchTweets: function(e) {
e.preventDefault();
var self = this;
var term = self.config.form.find('#term').val();
// grab tweets from the server
$.getJSON(self.url, { q: term }, function(data) {
self.displayTweets(data);
});
},
displayTweets: function(data) {
var self = this;
var tweetList = self.config.list;
tweetList.empty();
// append each tweet to the list
$.each(data.results, function(index, tweet){
$('<li></li>').text(tweet.text).appendTo(tweetList);
});
}
};
Tweets.init({
form: $('#getTweets'),
list: $('#tweets')
});
感謝您的回答,這是有道理的。欣賞它! – rabhw 2012-03-01 19:30:49