2012-02-13 140 views
1

一個對象的功能,讓我們說我有一個JavaScript的類是這樣的:解決在JavaScript事件處理程序

Foo.prototype = { 
    init: function() { 
    $(document).keydown(function(event) { 
     this.onKeyDown(event); 
    }); 
    } 

    onKeyDown: function(event) { 
    alert("bar"); 
    } 
} 

myObj = new Foo(); 
myObj.init(); 

此代碼將無法工作,因爲在

$(document).keydown(function(event) { 
    this.onKeyDown(event); 
}); 

了「這'當然是未知的,並沒有解決對象。無論如何,我怎樣才能解決Foo-Class的onkeydown方法?

我不想與'myObj'(對象的名稱)交換'this',因爲我可能想使用其他對象的類。

感謝您的幫助!

回答

4

儲存於一個變量...

Foo.prototype = { 
    init: function() { 
    var self = this 
    $(document).keydown(function(event) { 
     self.onKeyDown(event); 
    }); 
    } 
} 

或使用jQuery.proxy與綁定的this返回值的函數...

Foo.prototype = { 
    init: function() { 
    $(document).keydown($.proxy(function(event) { 
     this.onKeyDown(event); 
    }, this)); 
    } 
} 

,或者您可以使用Function.prototype.bind,但你」需要爲舊版瀏覽器打補丁。

Foo.prototype = { 
    init: function() { 
    $(document).keydown((function(event) { 
     this.onKeyDown(event); 
    }).bind(this)); 
    } 
}