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.
1 Answer 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');
}
}