I have an issuer where I lose the 'this' inside this 'object'. The output of the following piece of javascript gives me "some-id" and then "undefined". When I use 'this' inside a callback function, the scope goes out of the object and it cannot use 'this' anymore. How can I get the callback to use 'this' or at least have access to the object?
Since I will make multiple objects, I won't be able to create a 'static' like storage. Please help this javascript n00b ;-)
here is my test code that you can use to reproduce my problem. What I would like to have is CheckBox.doSomething()
to return the value of this.id
which should match some-id
for this test case.
function CheckBox(input_id) {
this.id = input_id;
this.doSomething();
$('#some-element').click(this.doSomething);
}
Checkbox.prototype.doSomething = function() {
alert(this.input_id);
}
var some_box = new CheckBox('some-id');
some_box.doSomething();
$('#some-element').click();
edit: I can't even get this to work as I want it to:
function CheckBox2(input_id) {
this.id = input_id;
alert(this.id);
}
CheckBox2.prototype.doSomething = function() {
alert(this.input_id);
}
var some_box = new CheckBox2('some-id');
some_box.doSomething();
Your problem is with this line:
$('#some-element').click(this.doSomething);
Why this is a problem
JavaScript methods don't know anything about the object that should be assigned to
this
, it's set when the method is called either explicitly (withmyFunction.call(obj)
) or implicitly (when called usingobj.myFunction()
).For example:
In your case, you're passing
this.doSomething
to jQuery, which is then explicitly calling it with the element that was clicked as the value ofthis
. What's happening is (a slightly more complex version of) this:The solution
You need to make sure that
doSomething
is called with the right value ofthis
. You can do that by wrapping it in another function:jQuery provides a
proxy
function lets you do this more simply:Others have already explained the causes of the problem and how to fix it with jQuery. What's left is how you fix it with standard JavaScript. Instead of ...
... you write:
This changes the context of
this
insidedoSomething
. You can also do that with anonymous functions - instead of ...... you write:
That has been very useful to me in projects with lots of callbacks, e.g. in Node.js (where you don't have to care about outdated browsers).
Edit:
getElementById()
andaddEventListener()
instead of$(...).click(...)
.The "javascript equivalent" of this is
Function#bind
but that is not available in every browser and since it seems you are using jQuery I am using the jQuery equivalent$.proxy