By himanshu123JavaScript
this keyword in javascript
What is this in java script
๐ฅ This depends on how a function is called, not where it is written.
- 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
This can be understood by practical example , their is not proper definition of it.
Example 1 - Playing with variable and function
var a = 5;
function hi() {
let a = 10;
console.log(a); //scope is the parent function
console.log(this.a); //scope is the scope of the parent function i.e window object
}
hi();
// output
// ----------
// 10
// 5
//Checking the same code with arrow function
var a = 50;
const hi = () => {
let a = 100;
console.log(a); //scope is the parent function
console.log(this.a); //scope is the scope of the parent function i.e window object
};
hi();
// output
// ----------
// 10
// 5
In short , this keyword scope is same as its parent scope.
Example - Adding one function inside another :
var a = 5;
function hello() {
var a = 10;
function hi() {
console.log(a);
console.log(this.a);
}
hi();
}
hello();
// this will always point global scope
Example 2 - Playing with objects
var name = "shekhar";
const obj1 = {
name: "Himanshu",
age: 24,
getMe() {
console.log("get me", this.name);
},
};
obj1.getMe();
//output -
//get me Himanshu
Example 3 - Playing with function inside object
Inside object ,
normal function refers to parent scope
arrow function refers to global scope
var name = "john";
const obj1 = {
name: "rock",
age: 24,
getDetails() {
var name = "rey";
console.log("One", this.name);
},
func1: {
name: "edge",
getMe() {
console.log("Two", this.name);
},
},
};
obj1.getDetails();
obj1.func1.getMe();
//output
//john
//get me edge
Arrow function with object :
var name = "himanshu";
var demo2 = () => {
var name = "shekhar";
var demo3 = () => {
console.log(this.name);
};
demo3();
};
demo2();
Output based question
Ques :
var a = 10;
console.log(this.a)
Ques -
const user = {
firstName: "Him",
getName() {
const firstName = "Shekh";
return this.firstName
},
};
console.log(user.getName());
//Him
Ques-
function makeUser() {
return {
name: "Himanshu",
ref() {
return this;
},
};
}
let user = makeUser();
console.log(user.ref().name);
Ques
const object = {
message: "Hello, World!",
logMessage() {
console.log(this.message); // What is logged?
},
};
setTimeout(object.logMessage, 1000);
Ques-
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?
Ques -
var name = "himanshu";
var street = 50;
var city = "kolkata";
var obj = {
name: "shekhar",
street: 46,
city : "agra",
sum1: function () {
console.log("normal fun", this.street);
},
sum2: () => {
console.log("arrow fun" , this.street);
},
address : {
houseName : "pathak lane",
landmark : "icici bank",
city : "ranchi",
place : function() {
console.log(this.city)
}
}
};
obj.sum1()
obj.sum2();
obj.address.place();
Ques 4 : this and arrow function
const bfObject = {
value: 42,
gfFunction: function() {
setTimeout(function() {
console.log("Result: ", this.value);
}, 1000);
},
}
bfObject.gfFunction();
- SolutionReason - This is because of how the this keyword behaves in JavaScript. In this context, inside the setTimeout function, this does not refer to bfObject as might be expected. Instead, it refers to the global object (in non-strict mode) or undefined (in strict mode).Solution -With this modification, the output will correctly be "Result: 42", as the arrow function retains the this value from its lexical context, which in this case is bfObject. const bfObject = { value: 42, gfFunction: function() { setTimeout(() => { console.log("Result: ", this.value); }, 1000); }, } bfObject.gfFunction();
Ques - Compare 2 objects
const obj1 = {
name: "him",
roll: "19",
};
const obj2 = {
name: "him",
roll: "19",
};
- Solution1ST WAY ----------- const obj1 = { name: "him", roll: "19", }; const obj2 = { name: "him", roll: "19", }; const isEqual = () => { const obj1Key = Object.keys(obj1); const obj2Key = Object.keys(obj2); if (obj1Key.length != obj2Key.length) { return "Not same"; } for (let objKey of obj1Key) { if (obj1[objKey] !== obj2[objKey]) { return "not same"; } } return "object are same"; }; console.log(obj1 == obj2); console.log(obj1 === obj2); const manualCompare = isEqual(); console.log(manualCompare); 2ND WAY ---------- const useLodashFun = _.isEqual(obj1, obj2); console.log(useLodashFun);
Ques (asked in epam)
const obj = {
name : "Jhon" ,
sayHi : function(){
const greet = function(){
console.log("hello "+ this.name)
}
greet();
}
}
obj.sayHi();
Ques
//Input:
const users = [
["David", "USA", 30],
["Billy"', "Japan", 35),
["Mike", "Singapore", 50]
];
//Output:
/*
[{
"name": "David"
"country": "USA",
"age": 30
},
{
"name": "Billy"
"country":"Japan"
"age": 35
},
{
"name": "Mike"
"country": "Singapore"
"age": 50
}
]
*/
Ques
const obj = {
value: 42,
regularMethod: function () {
setTimeout(function () {
console.log(this);
}, 3000);
},
};
obj.regularMethod();
Ques
const {firstName, lastName} = {firstName:"john", lastName:"kennedy"};
console.log(firstName); // john
****
Ques : How do you create an object using prototypal inheritance in JavaScript ?
let person = {
name: 'John',
age: 30,
greet: function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old`);
}
};
let employee = Object.create(person);
employee.jobTitle = 'Software Developer';
Find the output
let person = {
name: 'John',
age: 30,
greet: function() {
console.log('Hello, my name is ' + this.name + ' and I am ' + this.age + ' years old.');
}
};
person.greet();
Ques - tell the output
let name = "hs";
let user = {
name: "what about coding",
deep : {
wac1: () => {
console.log("arrow func " + this.name); // no 'this' binding here
},
},
wac2() {
console.log("normal func " + this.name); // 'this' binding works here
},
};
user.deep.wac1();
user.wac2();