javascript – What is apply() for – jquery

Question:

I would like to know what the apply() function in jquery is for.

I'm creating a plugin where I'm using. By observation I see that it takes the this and passes it as an argument in the init function. Then I can use this instead of opcao in the function.

But I would like to know who knows, what is the real function and when should I use it?

(function( $ ){
   var methods = {
        init:function(opcao){
            this.find("input").each(function(i,v){

                console.log(i);
                console.log($(v).appendTo("p"));

            }); 
        },
    }

   $.fn.input = function(method) {      

        console.log(this)
        return methods.init.apply( this, arguments );

    }; 
})( jQuery );

Answer:

.apply() is not from jQuery but a very useful and powerful method native to JavaScript to call a function by changing its scope, and at the same time passing arguments as the second parameter in an array.

That is, if you have this function:

function teste(a, b){
    console.log(this, a, b);
}

I can call this function normally with teste(1, 2); and then this will have the same value as this in the scope/line where I invoked the function.

But if you use .apply() the results are different:

teste.apply(document.body, ['foo', 'bar'[); // o this refere-se ao document.body
teste.apply(window, [1, 2]); // o this refere-se ao objeto window

In your example when you have return methods.init.apply( this, arguments ); what is happening is that this method methods.init will have the same scope as $.fn.input is called and pass it the same arguments. Notice that the arguments keyword is an array with all the parameters the function was called with.

Scroll to Top