[英]“this” keyword inside javascript callback function
我對“ this”關鍵字有很好的理解,但是由於某種原因,在這種情況下它仍然使我感到困惑。 在bindEvents方法內部,當我將Submit事件綁定到表單時,它隨后執行fetchTweets。 我知道,現在它位於“ on”方法的回調函數中,因此“ this”現在是指事件綁定到的形式,而不是父對象“ Tweets”。
我的理解是,通常的做法是在方法的頂部聲明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')
});
代替使用self.<member>
,嘗試使用Tweets.<member>
。 您不能在方法內部進行var self = this
,因為this
已經不是Tweets
。 但是,由於您有一個變量來引用要創建的對象,因此可以使用它。 :)
您還可以將事件處理程序包裝在匿名函數中,如下所示:
self.config.form.on('submit', function(e) { self.fetchTweets(e); });
然后不要做var self = this;
除了綁定處理程序的方法以外,其他任何方法都可以。 使用this
是安全的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.