4

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 :/

Justin Johnson
31.3k7 gold badges67 silver badges89 bronze badges
asked May 21, 2010 at 19:19
1
  • Just to be picky... JS does not have classes, it has prototypes. Commented May 21, 2010 at 19:23

1 Answer 1

8

Do this instead:

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

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

answered May 21, 2010 at 19:23
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.