Skip to content Skip to sidebar Skip to footer

Advantage Of Object.method(arg) Vs Method.apply(object, [arg])?

Is there an advantage to using call() or apply() instead of object.method()? Can someone provide an example of a situation where one would be preferred over the other? I'm reading

Solution 1:

As you've written it, there is no advantage to using call() or apply(). Calling the method directly makes more sense and is easier to read.

call() and apply() are basically used to explicitly control what object this refers to in the context of the function. Let's say in your example, you didn't want to make greeting a property of the myName object. Then you would have to use call() or apply():

function sayHello(x) {
    console.log("Hello, " + this.first_name + "." + x);
}

var myName = {
    first_name: "John",
}

sayHello.call(myName, 'How are you?');
sayHello.apply(myName, ['How are you?']);

Or you could use it to call a method on a different object:

function sayHello(x) {
    console.log("Hello, " + this.first_name + "." + x);
}

var myName = {
    first_name: "John",
    greeting: sayHello,
}

var herName = {
    first_name: "Mary",
}

sayHello.call(herName, 'How are you?');
sayHello.apply(herName, ['How are you?']);

// you could even get weird...
myName.greeting.call(herName, 'How are you?');
myName.greeting.apply(herName, ['How are you?']);

As far as the difference between call() and apply(), it's just how the arguments are handled. If you know the arguments beforehand, you can just use call() and pass them in as arguments. If your arguments are variable, you can collect them in an array and use apply(). The canonical example of this is finding the max of an array of numbers:

var nums = [ 3, 17, 5, -10, 16 ];
Math.max.apply(null, nums);

I hope this helps!


Solution 2:

call and apply as said in other answers allow you to define this for the related function.

jQuery is a great example of this usage as you can access a DOM element in a callback , it allows $(this)

Also apply is very powerful because it is a great tool when it comes to calling a function with a variable number of known arguments.

More generally call and apply are often used for method borrowing and a popular example is to use SomeConstructor.call(this) within a function to partially apply inheritance.


Solution 3:

Using call and apply lets you specify the context of the function where invoking it directly the context will be the current scope of "this".

Take a look at the docs.


Post a Comment for "Advantage Of Object.method(arg) Vs Method.apply(object, [arg])?"