What is ‘THIS’ Behavior JavaScript?
One of the keywords in JavaScript is ‘this’ and it can give you a hard time if you don’t understand it well.
The keyword ‘this’ is an essential part of object-oriented languages but ‘this’ in javascript works differently than ‘this’ keyword of java or ‘self’ in python.
In Javascript ‘this’ refers to the object in the context. In other words in a function, ‘this’ refers to the object containing it.
Now In Javascript, the value of ‘this’ depend how it is being used
- Inside a method
Functions defined inside an object are called methods.
when ‘this’ is used inside a method, it refers to the owner object. Let’s understand this with an example.
In the above example, ‘this’ in the greeting method refers to greet object.
2. Inside a function
This is where ‘this’ start getting confusing. so let’s understand with an example.
In the above code, we have a function dostuff() and what it does is, it prints the object containing the function. In the above example ‘Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}’ is printed out on the console. so if a function is not invoked by an object than it refers to the window object. Not just functions if a variable is defined outside the scope, it gets attached to the window object (a global object).
The keyword ‘this’ can work little differently inside a function also if the ‘strict mode’ is invoked for that function, ‘this’ is undefined. Here is an example.
You can get more info about strict mode here
3. Using this outside a function
If ‘this’ is used outside of a function or object then ‘this’ refers to window object and then it can access properties of the window object. Here is an example.
4. In an event
User interaction on Webpages is handled through events that occur when the user or the browser manipulates a page.
Events on a webpage can be of many types. some of them are click events, pressing of a key, loading of the webpage, etc.
In an event ‘this’ refers to the HTML element that received the event. for example <button onclick="doSomething(this)"> CLICK ME!</button>
Let’s see what is going on with the above example. whenever the button is clicked doSomething() function is called to do some magic on the screen and if that function contains ‘this’ inside then it will refer to the element which raised the event. That is why when an event is raised it refers to that element because that element is also an object inside the DOM(Document Object Model).
At last, Thanks for reading all the way through. Here you can read more about ‘this’. Here is a youtube video from freecodecamp on ‘this’.