1

Out of the following 2 ways of calling a method in JavaScript;

  1. myFunc(params);
  2. obj.myFunc();

My questions are;

  1. For each of them, what exactly is the difference in accessing the values (for params/obj) inside myFunc()
  2. For the 1st case, when we use "this" inside myFunc(), it would refer to global obj (window). What about the second case?
  3. What are the use cases for using either of the 2 techniques?

You can add any other significant differences between the two techniques as well.

halfer
  • 19,824
  • 17
  • 99
  • 186
copenndthagen
  • 49,230
  • 102
  • 290
  • 442

2 Answers2

1

Since you did not provide enough context, I will assume your two function calls:

1. myFunc(params)
2. obj.myFunc()

correspond to the following definitions of myFunc() and obj.myFunc():

function myFunc(params) { }

var obj = {
    myFunc: function() { }
};

The first call myFunc(params) is a call to the global function myFunc() with params passed as the parameter. this will refer to the global object, which is window inside browsers (You can test this by doing window.myFunc === myFunc, which will return true)

The second call obj.myFunc() is call to the method myFunc() inside the obj object. this will refer to obj, not window.

Regarding use cases, that will depend on your design, but global functions are obviously not recommended as they pollute the global namespace (i.e. you may redefine the global myFunc() by accident without noticing it).

The second approach is common when you need a pseudo javascript namespace

Community
  • 1
  • 1
rexcfnghk
  • 14,435
  • 1
  • 30
  • 57
-2

I will re-render your questions:

3- Cases: your_obj.function(): this one is usually used in the single page web app or you have many module one one page and you want to separate modules for maintaining purposes. While myfunction(args) is a global usage.

2 - you can invoke it by: window.your_obj.function()

1 - I'm not sure what you mean :)

Those are my opinion.

Phong Vo
  • 1,078
  • 7
  • 16