0

Just looking throug some js code file that has all it's code wrapped like that:

(function(self) {

//..

})(typeof self !== 'undefined' ? self : this);

Can you explain what is the javascript code above means:

What is self and where it is coming from?

What is the last line is actually does (typeof self !== 'undefined' ? self : this); ?

ricky
  • 1,644
  • 1
  • 13
  • 25
Sergino
  • 10,128
  • 30
  • 98
  • 159

1 Answers1

0

console.log(self);

console.log(this);
(function(){

})();

this is the syntax for IIFE in javascript (Immediatelyinvoked function expression).

Now ..

 (function(x){

    })(y);

now first () contains the actual anonymous function , and second () is used to call that function. WHat you pass in second get received by first.

So,

(function(self) {

//..

})(typeof self !== 'undefined' ? self : this);

typeof self !== 'undefined' will check if self (Browser global object) is existing or not. If its existing its passed otherwise this the scope of the object or global scope is passed.

self and this will provide same object here at root.

Atul Sharma
  • 9,397
  • 10
  • 38
  • 65