Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass $this to function

How can I pass the $this (the self keyword) to a function in Jquery

$(document).ready(function() {

    $('.nav a').click(function() {
        var direction = $(this).attr("name");
        submit_form($(this))
    }); 

    function submit_form(this)
    {
        // do some stuff with 'this'
    }       
});
like image 759
TMP file guy Avatar asked Jul 30 '10 16:07

TMP file guy


People also ask

How do you pass this keyword as parameter in JavaScript?

The main purpose of call() and apply() is to set the context of this inside a function irrespective whether that function is being called in the global scope or as object's method. You can pass an object as a first parameter in call() and apply() to which the this inside a calling function should point to.

Can you pass functions as parameters in JavaScript?

Conclusion. Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.


1 Answers

Wrapping it in $() makes it a jQuery object. You would want to do something like

submit_form(this);

function submit_form(obj)
{
    // Work with `obj` as "this"
    // Or wrap it in $() to work with it as jQuery(this)
}
like image 84
Josh K Avatar answered Oct 11 '22 12:10

Josh K