1

I have been using these lines in my projects but i do not know what does it exactly means, can anyone please tell me what does it mean exactly.

var myObject = window.myObject || {};

(function () { 

  //....my logic will go here

}).call(myObject);
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
zain222
  • 11
  • 2

2 Answers2

0
 var myObject = window.myObject || {};

That declares myObject on the global scope. If it was existing before it takes the existing value, or if it is not existing it assigns it to a new empty object (Read on). This is a common technique if multiple scripts assign properties of the same object, so that it doesn't matter which script got executed first they will always end up with the same result.

(function() { }).call(myObject)

Thats an IIFE were the context gets myObject, that allows you to write to the object easily with

this.someProp = someValue;

The IIFE also makes sure that your variables that you declared inside the function, e.g.:

var someValue = 1;

are not part of the global scope, so they are not polluting the global namespace.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0
var myObject = window.myObject || {}; // 1

(function () {                        //2

  //....my logic will go here

}).call(myObject);                    //3
  1. Create a variable called myObject from an existing myObject property of the window (DOM window) object or, if this does not exist, create a new empty object ({}).
  2. Declare an immediately-invoked function expression (IIFE).
  3. Call the IIFE by supplying the previously object myObject created (or retrieved from window if it was available there).

Notice that inside the IIFE you can access myObject as you wish. See in the below snippet how the printed object is the one created with a key custom and a value associated value.

var myObject = window.myObject || {
  custom: 'value'
};

(function() {

  console.log(myObject);

}).call(myObject);
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80