Roy
Roy

Reputation: 533

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.

Upvotes: 3

Views: 89

Answers (2)

user4639281
user4639281

Reputation:

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...

Upvotes: 3

JJJ
JJJ

Reputation: 33153

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...

(i.e. 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;

Upvotes: 2

Related Questions