What is apply () - jquery

3

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 this and passes as argument in function init . Then I can use this instead of opcao in function.

But I would like to know who you know, 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 );
    
asked by anonymous 12.05.2015 / 22:20

1 answer

3

.apply() is not jQuery but rather a very useful and powerful JavaScript native method 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 the this will have the same value as the this in the scope / line where I invoked the function.

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

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 methods.init method will have the same scope as $.fn.input is called and passes the same arguments to it. Notice that the reserved word arguments is an array with all the parameters the function was called.

    
12.05.2015 / 22:27