I have been using following code but what does it mean in javascript?

114
June 27, 2018, at 11:40 PM

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);
Answer 1
 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.

Answer 2
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);

READ ALSO
How to get live row count as Jasper prints reports

How to get live row count as Jasper prints reports

I've developed a web application using jsp that has a list of contents which are placed in an ArrayList

107
pygame elipse has gone wrong

pygame elipse has gone wrong

I am trying to make a simple pygame Tic Tac Toe gameThe following code is not finished

75
if else statement in the controller not responding in Laravel

if else statement in the controller not responding in Laravel

am trying to prevent a logged in user from accessing some passages exception the user has his information in the NextofKin table by using this method in my controller

54