0

I'm trying to create a javascript class and instantiate some objects of it from HTML on load. The class contains some functions and some event listeners.

function Rating (id) 
{
 this.id = id;
 $(id).click(function() 
 {
 alert('click '+ this.id);
 this.debug();
 });
 this.debug = function() 
 {
 alert(' debug');
 }
 }

My goal is to call a class function from an event listener (in this case debug inside click listener). Unfortunately, when I click on the object I only see the event-listener alert and not debug alert (fiddle).

I know it's a basic question. But all answers I've found explain to create classes as variables, not as functions. I've adopted this way because my goal is to create multiple instances of the class into the same page. Is there a way to instantiate multiple objects using "variable classes" and call internal functions from objects? Thanks in advance.

asked Apr 28, 2014 at 9:49

1 Answer 1

1

Classical one, the context in the event handler is window.

The simplest solution is to declare a variable in the enclosing scope to store the value you need :

function Rating (id) 
{
 var r = this;
 this.id = id;
 $(id).click(function() {
 alert('click '+ r.id);
 r.debug();
 });
 this.debug = function() 
 {
 alert(' debug');
 }
 }
Sign up to request clarification or add additional context in comments.

3 Comments

If someone finds a good QA to close this Q as duplicate and it gets closed, I'll delete this answer.
Thanks @dystroy. I would have preferred to avoid asking, but as said I wasn't able to find answers with "function classes", only variables.
@Giorgio I wasn't insulting you, this is one of those things that are hard to search or figure at first.

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.