In global exception context, this and window object are by default created –
“this” keyword
"this" keyword refers to the object it belongs to
- By default , this refers to the global object
- Inside normal function , it refers to the global object
- Inside arrow function, this refers to the global object
- Inside object,
– this refers to the parent object
– normal function refers to the parent scope
– arrow function refers to the global scope - and so on
Let’s understand “this” with an example
Global or Alone
console.log(this);
Inside Normal Function
Inside normal function -
function demo1() {
function demo2() {
function demo3() {
console.log(this);
}
demo3();
}
demo2();
}
demo1();
Inside Arrow Function
var name = "himanshu";
var demo2 = () => {
var name = "shekhar";
var demo3 = () => {
console.log(this.name);
};
demo3();
};
demo2();
Inside Object
var name = "himanshu";
var obj = {
name: "shekhar",
roll: 46,
sum1: function () {
console.log(obj.roll);
console.log("normal fun", this.name);
},
sum2: () => {
console.log("arrow fun", this.name);
},
};
// console.log(obj.sum());
obj.sum1();
obj.sum2();
Practice
Question 1 –
var a = 10; console.log(this.a)
Question 2-
var name = "himanshu"; var roll = 50; var obj = { name: "shekhar", roll: 46, sum1: function () { var roll = 48; console.log("normal fun", this.roll); }, sum2: () => { console.log("arrow fun", this.roll); }, }; obj.sum1(); obj.sum2();
Question 3 –
const object = { message: "Hello, World!", getMessage() { const message = "Hello, Earth!"; return this.message; }, }; console.log(object.getMessage()); // What is logged?
Question 4 –
While setTimeout() function uses the object.logMessage as a callback, still, it inovkes object.logMessage as a regular function, rather than a method.
const object = { message: "Hello, World!", logMessage() { console.log(this.message); // What is logged? }, }; setTimeout(object.logMessage, 1000);
Question 5 –
const object = { who: 'World', greet() { return `Hello, ${this.who}!`; }, farewell: () => { return `Goodbye, ${this.who}!`; } }; console.log(object.greet()); // What is logged? console.log(object.farewell()); // What is logged?