Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redefine `this` in Javascript?

I have a function which is a JQuery event handler. Because it is a JQuery event handler, it uses the this variable to refer to the object on which it is invoked (as is normal for that library).

Unfortunately, I need to manually call that method at this point. How do I make this inside the called function behave as if it were called from JQuery?

Example code:

function performAjaxRequest() {
    //Function which builds AJAX request in terms of "this"
}

function buildForm(dialogOfForm) {
    var inputItem;
    dialogOfForm.html('...');
    dialogOfForm.dialog('option', 'buttons', {
        "Ok" : performAjaxRequest
    });
    inputItem = dialogOfForm.children(':not(label)');
    //Redirect enter to submit the form
    inputItem.keypress(function (e) {
        if (e.which === 13) {
            performAjaxRequest(); //Note that 'this' isn't the dialog box
                                  //as performAjaxRequest expects here, it's
                                  //the input element where the user pressed
                                  //enter!
        }
    }
}
like image 303
Billy ONeal Avatar asked Oct 13 '10 01:10

Billy ONeal


3 Answers

You can use the function's call method.

someFunction.call(objectToBeThis, argument1, argument2, andSoOnAndSoOn);
like image 168
Chuck Avatar answered Oct 17 '22 22:10

Chuck


If dialog is the object that you need to be set to this then:

performAjaxRequest.apply(dialog, []); 
// arguments (instead of []) might be even better

should do the trick.

Otherwise, in jQuery you can simply call the trigger method on the element that you want to have set to this

Say, for example, that you wanted to have a click event happen on a button and you need it to happen now. Simply call:

$("#my_button").trigger("click");

Your #my_button's click handler will be invoked, and this will be set to the #my_button element.

If you need to call a method with a different this ... say for example, with this referring to the jQuery object itself, then you will want to use call or apply on your function.

Chuck and meder have already given you examples of each ... but to have everything all in one place:

// Call
my_function.call(object_to_use_for_this, argument1, argument2, ... argumentN);

// Apply
my_function.apply(object_to_use_for_this, arguments_array);

SEE: A List Apart's Get Out of Binding Situations

like image 22
Sean Vieira Avatar answered Oct 17 '22 21:10

Sean Vieira


Are you looking for..

functionRef.apply( objectContext, arguments);
like image 4
meder omuraliev Avatar answered Oct 17 '22 23:10

meder omuraliev