+ 1
Can someone explain this code please ( self.self === self)
From: https://github.com/eligrey/FileSaver.js/blob/master/src/FileSaver.js Can someone explain line by line what this code is doing? // The one and only way of getting global scope in all environments // https://stackoverflow.com/q/3277182/1008999 var _global = typeof window === 'object' && window.window === window ? window : typeof self === 'object' && self.self === self ? self : typeof global === 'object' && global.global === global ? global : this Thank you
4 Réponses
+ 3
`typeof window === 'window'` means that this code runs when `window` exists. That means we are in a browser environment.
if `self` is defined, we are in we WebWorker environment.
if `global` is defined, we are inside a nodejs environment.
+ 2
This is ternary operater.
var _global = " " ;
if(typeof window === 'object' && window.window ===window) {
return window
if(typeof self === 'object' && self.self === self) {
return self
if(typeof global === 'object' && global.global === global) {
return global
} else {
return this
}
}
0
Schindlabua thank you for explaining it, where I can read more about that. Can you provide the source of your information please?
0
Regarding window and self:
https://developer.mozilla.org/en-US/docs/Web/API/Window/self
Regarding global:
https://nodejs.org/api/globals.html#globals_global
The problem is that sometimes we need to store stuff in the global namespace and for that we need the "global" variable but javascript runs in many places and they each behave differently so we have to play detective and check which variables exist. The TC39 (the people who define new javascript standards) are currently standardizing the global variable and it's just `globalThis` everywhere now so you can use that instead. (Beware of old environments like un-updated browsers like Internet Explorer)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
https://github.com/tc39/proposal-global/blob/master/README.md
I haven't read through this article but it's long and seems to cover all the subjects in a bit more detail than I can fit here: https://www.contentful.com/blog/2017/01/17/the-global-object-in-javascript/