Transfer method for function

In Javascript, I am trying to pass a class member to a jQuery function, but somehow the 'this' object in this function is confused. 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 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 triggered the keydown event.

Somebody knows? I am puzzled: /

+4
source share
1 answer

Do this instead:

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

And then read this to explain how this works in different contexts.

+8
source

Source: https://habr.com/ru/post/1310559/


All Articles