0

Today I have come across two ways of calling an object method.
This I have seen in a kind of API which when expose certain functions to the external world. In those methods I have found following way obj.MyFn.apply(obj, arguments) to call the encapsulated methods which they dont want to expose to the outside world.

So my question is:
What is the difference(context here is in terms of encapsulation of API's internal methods, here its MyFn) between following two ways of calling a method of an object?

  1. obj.MyFn() and
  2. obj.MyFn.apply(obj, arguments);

Assumption: I have an object obj having defined a method named as MyFn.

Ghan
  • 60
  • 8
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Description – GrafiCode Jun 18 '19 at 15:01
  • 1
    Possible duplicate of [Why invoke "apply" instead of calling function directly?](https://stackoverflow.com/questions/5936604/why-invoke-apply-instead-of-calling-function-directly) – str Jun 18 '19 at 15:01
  • One passes some arguments, the other does pass no arguments. Regarding the `this` value, they're the same. And in modern JS, you'd just write `obj.MyFn(...arguments)` – Bergi Jun 18 '19 at 15:02
  • Thanks @str for quick reply. My question is more towards the encapsulation of the api internal methods. None of the answers of the question you suggested provide those details. So I think this is different context and just wanted to know if this way we can provide more encapsulation ?? – Ghan Jun 18 '19 at 15:15
  • Thanks @Bergi. The question is more towards the encapsulation of the api internal methods or both of the ways just do the same thing? – Ghan Jun 18 '19 at 15:16
  • 2
    @Ghan There is no other difference, no "encapsulation". You might want to post the complete code that you are referring to, or at least link the library code that you wonder about. – Bergi Jun 18 '19 at 15:18
  • @Bergi Its a internal library to our project. so can't put here but will try to create some snippets around it. Till the time you can think of it as an IIFE which has some logic and returns an object containing exposed methods, these exposed methods call some others methods using .apply(). – Ghan Jun 18 '19 at 15:26
  • @Ghan Well, sounds like they a) want to call the methods on the un-exposed `obj` and b) still want to pass arguments through. The alternative would've been exposing `bind()`ed methods. – Bergi Jun 18 '19 at 15:28

0 Answers0