2010-05-21 119 views
4

在JavaScript中,我試圖傳遞一個類成員到一個jQuery函數,但不知何故該函數中的'this'對象會搞砸。這是代碼:傳遞函數到函數

function Hints() 
    { 
    this.markProduct = function() { alert('hi'); }; 
    this.selectProduct = function() { this.markProduct(); }; 
    } 

當我打電話使用此驗證碼:

oHints = new Hints(); 
oHints.selectProduct(); 

它工作得很好,並在「selectProduct」功能「這個」對象是指提示對象。 但當我嘗試這個辦法:

oHints = new Hints(); 
$('#prodquery').keydown(oHints.selectProduct); 

在「selectProduct」功能「這個」對象是指射出的keydown事件的HTML對象。

有沒有人有線索?我很疑惑:/

+0

只是要挑剔... JS沒有類,它有原型。 – nico 2010-05-21 19:23:03

回答

8

而是執行此操作:

$('#prodquery').keydown(function() { oHints.selectProduct() }); 

然後read this在不同的情況下如何this作品的解釋。

+0

感謝您的答案,並感謝您的鏈接! :) – acidtv 2010-05-21 19:38:36