2
我這裏有一些代碼:有什麼處理「這個」不使更多的標準「即」參考「這個」
App.prototype.binds = function(){
var that = this;
$('.postlist li').live('click', function(){ that.selectPost(this);});
}
App.prototype.selectPost = function(){
this.function();
}
我創造「這個」是「」在的參考我的綁定函數,所以在我的selectPost(),我可以使用「this」來引用應用程序對象,而不是列表項。
有沒有更優雅/標準的解決方案,而不是使用「那個」?
的答案,我的代碼就變成了:
function App() {
this.selectPost = this.selectPost.bind(this);
//$.proxy(this.selectPost, this) in jQuery
}
App.prototype.binds = function(){
$('.postlist li').live('click', this.selectPost); //Already bound in constructor
}
只是
在構造函數中:
App.prototype.binds = function(){
$('.postlist li').live('click', $.proxy(this.selectPost, this));
}
App.prototype.selectPost = function(e){
this.function(); // function in App
var itemClicked = e.currentTarget; //or
var $itemClicked = $(e.currentTarget);
}
* *表示標準。 (或* self *,或* $ this *) – ahren