Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript callbacks losing 'this'

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();
like image 775
Anyone Avatar asked May 26 '12 12:05

Anyone


People also ask

Can we use this in callback?

Don't use this Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback.

What is the problem with callbacks?

This is a big issue caused by coding with complex nested callbacks. Here, each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain.

What is a callback in JavaScript?

JavaScript Callbacks. ❮ Previous Next ❯. "I will call back later!". A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

What does I will call back later mean in JavaScript?

"I will call back later!" JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined. Sometimes you would like to have better control over when to execute a function. Suppose you want to do a calculation, and then display the result.

What are anonymous callbacks in JavaScript?

A callback can be an anonymous function, which is a function without a name like this: In this example, we pass an anonymous function to the filter () function instead of using a separate function. There are two types of callbacks: synchronous and asynchronous callbacks.

Why are the callbacks simplified?

They are simplified to teach you the callback syntax. Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like waiting for a file to load). Asynchronous functions are covered in the next chapter.


1 Answers

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 (with myFunction.call(obj)) or implicitly (when called using obj.myFunction()).

For example:

var x = {
    logThis: function () {
        console.log(this);
    }
};

x.logThis(); // logs x
x.logThis.call(y); // logs y

var func = x.logThis;
func(); // logs window: the fallback for when no value is given for `this`

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 of this. What's happening is (a slightly more complex version of) this:

var callback = this.doSomething;
callback.call(anElement, anEvent);

The solution

You need to make sure that doSomething is called with the right value of this. You can do that by wrapping it in another function:

var cb = this;
$('#some-element').click(function() {
    return cb.doSomething();
});

jQuery provides a proxy function lets you do this more simply:

$('#some-element').click(jQuery.proxy(this.doSomething, this));
like image 120
georgebrock Avatar answered Oct 20 '22 00:10

georgebrock