'this' Keyword JavaScript Notes
'this' keyword JavaScript Notes
'this' keyword works differently in different Scope.
'this' in global Scope
console.log(this)
output-
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
'this' in strict and non-strict mode
'this' keyword works differently in strict and non-strict mode.
"use strict"
function x(){
console.log(this);
}
x();
output- undefined
non-strict mode
output- Window {window: Window, self: Window, document: document, name: '', location:
Location, …}
Point to be noted-
"If at any point the value of 'this' keyword is undefined or null. the value will be replaced with global object only in non-strict."
Interview Question-
What is the value of this Keyword inside function?
Ans- The value of this keyword inside a function is undefined but JS has something calls this substitution so the value will become global object. if we don't use strict mode.
What is the difference between a function and a method?
Ans- If you make a function as part of an object then it is known as method.
Ex-
const obj = {
a:10,
x:function(){
console.log(this.a);
}
}
obj.x();
Output- 10;
Ex-
const obj2 = {
a:10,
x:function(){
console.log(this);
}
}
obj2.x();
Output- {a: 10, x: ƒ};
'this' inside arrow function
Arrow function does not have their own 'this'. they take the values of their lexical environment. where they are enclosed.
Example1
const obj3={
a:10,
x:()=>{
console.log(this);
}
}
obj3.x();
Output- Window {window: Window, self: Window, document: document, name: '', location: Location, …}
Inside arrow function this behaves like it preset inside global space because obj3 is inside global space.
Example2
const obj4={
a:20,
x:function(){
const Y = () =>{
console.log(this);
}
Y();
}
}
obj4.x();
Output- {a: 20, x: ƒ}
Point to be noted
arrow function doesn't provide their own this binding (it retains the value of 'this' enclosing lexical context.
'this' keyword inside DOM
'this' inside DOM elements give reference to HTML element.
<button onclick="alert(this)">Click Me</button>
Output-
Comments
Post a Comment