开发者

Pass method to function

开发者 https://www.devze.com 2022-12-31 11:48 出处:网络
In Javascript I\'m trying to pass a class member to a jQuery开发者_高级运维 function, but somehow the \'this\' object in that function gets messed up. This is the code:

In Javascript I'm trying to pass a class member to a jQuery开发者_高级运维 function, but somehow the 'this' object in that function gets messed up. This is the code:

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

When I call this code using this:

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

It works just fine and the 'this' object in the 'selectProduct' function refers to the Hints object. But when I try this:

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

The 'this' object in the 'selectProduct' function refers to the html object that fired the keydown event.

Does anyone have a clue? I'm puzzled :/


Do this instead:

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

And then read this for explanation of how this works in different contexts.

0

精彩评论

暂无评论...
验证码 换一张
取 消