What to apply() - jquery for

Asked

Viewed 551 times

4

I wonder what the function is for apply() in jquery.

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

But I’d like to know who you know, what your real job is and when to 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 );

1 answer

3


The .apply() not jQuery but a very useful and powerful Javascript native method to call a function by changing its scope, and at the same time passing arguments as a 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 on which I invoked the function.

But if you use the .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’s happening is that this method methods.init will have the same scope with which $.fn.input be called and pass the same arguments. Notice that the word reserved arguments is an array of all parameters with which the function was called.

  • 1

    So if I add parameters in the function, in the case of the object with default values, they will stay the same. Hence the defauts parameters I can leave inside the object>: methods. I will not need to create another object within $.fn.input .. ATT

Browser other questions tagged

You are not signed in. Login or sign up in order to post.