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)
1
  • apply doesn't change "context", it is used to set the value of a function's this to a particular value. Commented Aug 11, 2015 at 6:26

5 Answers 5

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}
Sign up to request clarification or add additional context in comments.

2 Comments

I can also pass the arguments in the first one.
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)
0

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

Comments

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?

1 Comment

"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.
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.