What is this and what context is it used?
To understand this segment, we will have to head to an IDE. For simplicity, I will be using the Eloquent JavaScript IDE on this link.
When the command console.log(this)
gives access to the Window object. The Window object represents an open window in the browser. The browser creates a window object for the HTML document and also all the tags that make up the HTML document. Click this link to have a look at Window Object Properties and Window Object Methods. console.log(typeof this)
returns Object. Below is the snippet of the actual window object logged.
They look very similar to W3Schools.com website link window objects properties and their methods.
console.log(this.origin)
returns https://eloquentjavascript.net
๐. Inside the window object, name leads to an empty string, hence console.log(this.name)
returns nothing since it's an empty string. A made up name on the other hand: console.log(this.anyName)
returns undefined
since there has not been any declaration to anyName and it does not exist in the window object. However, let anyName = 'myName'; console.log(this.anyName)
returns myName
๐ค.
Context
When this is used inside a function, it refers to an object in which it is bound. It simply refers the function to where it should get its data from.
Calling this function: let whyMe = 'It is getting clearer'; whatIsThis()
prints It is getting clearer
. However, we still have access to the window objects when needed even inside a function. It is worth noting that whyMe() is now bound to the global scope and this.whyMe references that global scope.
In the above code, name, action, toy and Function are all properties of myObject. Accessing this properties we can use the .dot
method. Hence accessing the function Function from myObject runs testing, which then receives global scope from the window and appends to the respective properties.
Hope this clears something the confusion for beginners.