0

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)
Rjindal
  • 41
  • 4
  • *apply* doesn't change "context", it is used to set the value of a function's *this* to a particular value. – RobG Aug 11 '15 at 06:26

5 Answers5

2

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}
Amadan
  • 169,219
  • 18
  • 195
  • 256
  • 1
    I can also pass the arguments in the first one. – Rjindal Aug 11 '15 at 06:16
  • In general, you will use `apply` to call functions/methods when you don't know how many arguments you will have. A common example is destructively concatenating an array: `concat` returns a new array, but if you want to concat by modifying an existing array, you'd use `push`: `array.push(3, 4)`. But if you have two arrays, you can't use `array.push(other)`; saying `array.push(other[0], other[1])` is stupid because you need to know it will never have more than 2 members, you cannot use the Ruby splat trick of `array.push(*other)`; so you need to apply `apply`: `array.push.apply(array, other)` – Amadan Aug 11 '15 at 06:20
0

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

potatopeelings
  • 38,000
  • 6
  • 80
  • 108
0

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?

Community
  • 1
  • 1
Himanshu Goel
  • 494
  • 8
  • 23
  • "*normally it takes the context of current object*". Nope. A function's *this* is set by the call, it's not related to the current (execution) context. Many functions are called without setting *this* so it defaults to the global object or *undefined* in strict mode. – RobG Aug 11 '15 at 06:29
0

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

0

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

Community
  • 1
  • 1
charlee
  • 1,103
  • 1
  • 8
  • 21