0

I noticed on Stack Overflow's JavaScript code editor, the global object has many members, including the normal global browser object, window.

How does it offer members of window directly (for instance Promise, as seen below), when the full path is in fact this.window.Promise?

console.log('this in top-level scope: ', this);
console.log('Promise constructor on window object, from top-level scope: ', this.window.Promise);
console.log('Still, grabbing Promise directly works: ', Promise);

1
  • 1
    this === window // true. window is the global scope and it has itself inside. window.window.window.window === window // true. Commented Jul 24, 2018 at 16:04

2 Answers 2

4

Because what you see is actually the global window itself which contains a self reference:

this === window
window.window === window

Thats how it is in every browser, thats not something special of SO snippets. Therefore it doesnt matter if you access it like:

Promise
window.Promise
this.window.Promise
this.window.window.Promise
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, Jonas. If what i see when logging this is in fact the window object, any idea why can't I find the Promise constructor on it? Shouldn't the global object implement ECMAScript defined standard built-in functions? If Promise is not on window, any idea where it resides?
@magnus what do you get if you do console.log(this.Promise); ?
You get the Promise object, but if you take the logged output from console.log(this) and paste it in a text/code editor and do a search for Promise, no object is found (at least not for me). setTimeout and other Web APIs are visible.
It's a non-enumerable property.
Interesting. I did console.log(Object.getOwnPropertyNames(this));, which prints both enumerables and non-enumerables, and I got all the expected matches, including Object, Function, Promise, etc.. The thing that threw me off here, is that in my Visual Studio Code editor (Windows box) console.log(obj) actually logs non-enumerables too.
|
1

the keyword 'this' in javascript refers to the current execution context, whatever that may be. If the current execution context is the global scope, this refers to window.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.