Rjindal
Rjindal

Reputation: 41

Javascript difference between calling a function directly and using apply

Both are calling the same function and in the same context, then what is the difference between in these statements.

this.subject.hello();

apply() is used to call the method in the different context. But here it is called in the same context.

this.subject.hello.apply(this.subject, arguments)

Upvotes: 0

Views: 87

Answers (5)

charlee
charlee

Reputation: 1369

Here are some great answers on topics of apply, call and JavaScript context:

Upvotes: 0

Riccio Zhang
Riccio Zhang

Reputation: 1

The only difference is that one with arguments and other one without.

Upvotes: 0

Himanshu Goel
Himanshu Goel

Reputation: 594

with apply we can change context of method, normally it takes the context of current object. context is passed as first parameter is apply method, and other parameters are passed inside a array which is second parameter in apply method.

for other queries between call and apply you can refer Stackoverflow question : What is the difference between call and apply?

Upvotes: 0

Amadan
Amadan

Reputation: 198324

The first one calls it with no arguments. The second one calls it with arguments of the current function.

this.subject = {
  hello: function() {
    console.log("Hello called with arguments " + JSON.stringify(arguments));
  }
};

function callHello() {
  console.log("this.subject.hello();");
  this.subject.hello();
  console.log("this.subject.hello.apply(this.subject, arguments);");
  this.subject.hello.apply(this.subject, arguments);
}

callHello(1, 2);
// => this.subject.hello();
//    Hello called with arguments {}
//    this.subject.hello.apply(this.subject, arguments);
//    Hello called with arguments {"0":1,"1":2}

Upvotes: 2

potatopeelings
potatopeelings

Reputation: 41065

The only difference is that in the first call you are not passing in any arguments.

Upvotes: 0

Related Questions