简体   繁体   中英

What is self-referential window property in client-side javascript?

I am studying a book on Javascript, " Javascript: The Definitive Guide - David Flanagan ". Chapter 3 of this book talks about the Global object, here, they say that

global Window object has a self-referential window property that can be used instead of this to refer to the global object.

What I understand from the above line is that window is not the object instead it is self-reference, but could someone explain me in detail how it is.. and how to create a self-referential property for a custom object.

Like in chrome console if I type in window i get

Window {top: Window, location: Location, document: document, window: Window, external: Object…}

How to achieve the same for custom objects. Sorry, if I understood this totally wrong please excuse me for that, I am newbie to JS.

Self-referential means that the Window object has a property which references itself.

window.window = window

When you're in the window scope, this === window so you can reference properties like window.location using the following methods.

  1. window.location
  2. this.location
  3. location
  4. window.window.location
  5. this.window.location
  6. etc...

You understood it wrong. It means that the window object has a member called window which is a reference to the window object itself. That is to say,

window.window === window

Adding some quotes to the quote might clarify it a bit:

global Window object has a self-referential "window" property...

(ie global Window object has a property called "window" that is self-referential.)

Although it's very rarely useful, to create one for a custom object you just assign itself to a member element.

var obj = {};
obj.obj = obj;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM