I’m a C++ guy just learning JavaScript, so the fact that ‘this’ is bound to the calling object continues to surprise. I want to use an object method as an event listener, and want to make sure I am doing it with all the style of you JavaScript professionals.
So, to get the method to have it’s objects ‘this’, so that I can access its properties in the proper context, I have written the following:
var user =
{
status: 1, // login status: 0:invalid password, 1:logged out, 2:logged in
loginName: "",
// Method called whenever the user submits a username/password via html form:
onLoginSubmit: function (event)
{
if (this != user) // called from 'form submit' callback, so call ourselves:
{
user.onLoginSubmit(event);
return;
}
}
};
I found a previous answer here: Accessing an object's property from an event listener call in Javascript, but the proposed solution is to basically create a global.
Is there a cooler, more professional way to get ‘this’ than the previous solution or my recursive solution?
I’m assuming that when you are binding the submit handler, you are doing something like this:
While what you have does work, the best way to do with would be to bind the submit handler so that it actually calls onLoginSubmit with the proper ‘this’, so that you don’t need any extra logic inside the submit handler.
If you do something like this when you bind the function, then it should work.
By using an anonymous function, you can still properly call the method of the user object.
If I’m misunderstanding your issue, please post a bit more code about how you are calling onLoginSubmit().