interview question on this
console.log("global",this); // window
console.log("window",window);
(function () {
console.log("inside iife",this); // window
})();
function abc(){
console.log("normal",this); // window
}
abc();
// --------
/*
in "use strict" mode if the function called without object
then "this" will be "undefined"
else "this" will be that "object"
*/
'use strict'
function abc1() {
console.log("abc1", this);
}
abc1() // undefined
window.abc1(); // // window
// -------
function Abc(){
console.log("normal",this); // Abc {}
}
/*
## constructor function
1: It creates a new empty object {}.
2: set "this" to this empty object.
3: By default, the function returns the newly created object (unless it explicitly returns something else)
*/
new Abc();
(function () {
'use strict'
console.log("with use strict and inside iife",this); // undefined
})();
const ArrowF=()=>{
console.log("ArrowF",this); // window // aways from parent scode with or without use strict
}
ArrowF();
Q1:
const person = {
name: "Alice",
greet: function () {
console.log(this.name);
},
};
const greet = person.greet;
person.greet(); // ?
greet(); // ?
Q2:
function showThis() {
console.log(this);
}
const obj = {
method: showThis,
};
showThis(); // ?
obj.method(); // ?
Q3:
const car = {
brand: "Toyota",
getBrand: function () {
const innerFunc = () => {
console.log(this.brand);
};
innerFunc();
},
};
car.getBrand(); // ?
Q4:
const obj = {
value: 100,
showValue: function () {
console.log(this.value);
function innerFunc() {
console.log(this.value);
}
innerFunc();
},
};
obj.showValue(); // ?
Q5:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(this.name);
}
}
const person = new Person("John");
const greet = person.greet;
person.greet(); // ?
greet(); // ?
Q6:
const team = {
members: ["Alice", "Bob"],
showMembers: function () {
this.members.forEach(function (member) {
console.log(this);
});
},
};
team.showMembers(); // ?