JS का globalThis
In this page:
globalThis.propertyName = value;
globalThis.propertyName;
globalThis क्या है
globalThis एक standard property है जो global object को refer करती है चाहे code किसी भी JavaScript environment में चले, जो पहले हर platform पर अलग-अलग नामों की मांग करता था उसे एक कर देती है।
उदाहरण: What Is globalThis
console.log(typeof globalThis); // "object" in every environment
Node.js में globalThis
Node.js में, globalThis उसी global object को point करता है जिसे आप वरना global के रूप में access करते, यह Node code को बिना किसी Node-specific identifier के global state refer करने का एक तरीका देता है जो browser में काम नहीं करेगा।
उदाहरण: globalThis in Node.js
// In Node.js: globalThis === global
console.log(typeof globalThis);
globalThis और Browser Code
browsers में, globalThis उसी object को refer करता है जो window है (या किसी worker के अंदर self), इसलिए browser code किसी खास browser global के मौजूद होने का मान लिए बिना इसे इस्तेमाल कर सकता है।
उदाहरण: globalThis and Browser Code
// In browsers: globalThis === window
console.log(globalThis === window);
Portable Global Access
चूंकि globalThis हर जगह बिल्कुल एक जैसा काम करता है, global object की जांच करने या उससे जुड़ने वाला code — जैसे कोई polyfill — environment-detection branching के बिना ऐसा कर सकता है।
उदाहरण: Portable Global Access
// Check whether `!globalThis.myPolyfill`
// Check whether `!globalThis.myPolyfill`
if (!globalThis.myPolyfill) {
// Assign `function () { return "polyfilled"; }` to `globalThis.myPolyfill`
// Assign `function () { return "polyfilled"; }` to `globalThis.myPolyfill`
globalThis.myPolyfill = function () { return "polyfilled"; };
}
// Print `globalThis.myPolyfill()` to the console
// Print `globalThis.myPolyfill()` to the console
console.log(globalThis.myPolyfill());
globalThis के साथ Best Practices
globalThis को सीधे छूने के बजाय explicit imports और modules को prefer करें; इसे सिर्फ genuine cross-environment library code के लिए रखें जिसे global object के साथ सुरक्षित रूप से interact करना ही हो।
उदाहरण: Best Practices with globalThis
// Prefer modules/imports over touching globalThis directly
import { helper } from './utils.js';
console.log(helper());
- ऐसे code में
windowइस्तेमाल करना जो Node.js में भी चलता है, जोReferenceErrorthrow करता है;globalThisइस्तेमाल करें। globalThisपर गलती से global properties बना देना, जो दूसरे scripts से clash कर सकती हैं।- यह उम्मीद करना कि top level पर
letऔरconstglobalThisपर दिखेंगे, जबकि सिर्फvarऔर function declarations ही दिख सकते हैं।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: