2

Is it possible to create a js object that is not under the window object? If yes, then how? There is a different ongoing discussion when I'm trying to understand the location of _internalRoot object created by ReactRoot() constructor. Good people say that most probably it's not under the window object.

I was sure that we could not create an object outside of a window object.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
platinum_ar
  • 127
  • 3
  • 8
  • You mean global object? – Marios Nikolaou Dec 01 '19 at 16:10
  • 3
    Only global variables (including top level variables declared with `var`) are implicitly added to `window`. A variable declared with `let` or `const` or a variable inside a function, E.G. `function ReactRoot ( ) { var _internalRoot = { }; }` is not added to `window`. – Paul Dec 01 '19 at 16:12
  • Thanks for all the explanation. The one last thing that bothers is that when I create an object like this, I can's see the "ReactRoot" on the list of constructors in a heap snapshot (chrome). – platinum_ar Dec 02 '19 at 18:30

2 Answers2

2

Just create the object in a local variable:

function example() {
    var demo = {};
}
example();

Even if example is a global variable and somehow tied to window, the demo variable is not.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for all the explanation. The one last thing that bothers me is that when I create an object inside a "ReactRoot" function, I can't see the "ReactRoot" on the list of constructors in a heap snapshot (chrome). – platinum_ar Dec 02 '19 at 18:38
  • Well, the object was not constructed through `demoObject = new ReactRoot`, but just *inside* a `ReactRoot` function. – Bergi Dec 02 '19 at 18:56
1

the easiest way is, create an immediately executing function(IIFE) and create your object in it.

(function() {
  var yourObject = {};
})();

more details on IIFE is here https://developer.mozilla.org/en-US/docs/Glossary/IIFE

gsaandy
  • 581
  • 4
  • 8