1.

Is JavaScript synchronous or asynchronous and what is event loop ?

Answer»

There are FOUR solutions to access “this” inside the innerFunc().

Solution 1
Use a “that” variable in CLEANROOM() for ACCESSING “this” inside innerFunc(). Basically “that” is nothing but the OUTER “this”.

const cleanRoom = function(soap) {   let that = this;   const innerFunc = function(_soap) {         console.log(`Cleaning ${that.room} with ${_soap}`)         }   innerFunc(soap); }   let harrysRoom = {   room: "Harry's room" } cleanRoom.call(harrysRoom, "HARPIC"); //Output - Cleaning Harry’s room with Harpic

Solution 2
Use call method to use the outer “this” inside the innerFunc().

const cleanRoom = function(soap) {   const innerFunc = function(_soap) {         console.log(`Cleaning ${this.room } with ${_soap}`)         }   innerFunc.call(this, soap); }   let harrysRoom = {   room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic

Solution 3
Use bind method to use the outer “this” inside the innerFunc().

const cleanRoom = function(soap) {   const innerFunc = function(_soap) {         console.log(`Cleaning ${this.room } with ${_soap}`)         }   innerFunc.bind(this)(soap); }   let harrysRoom = {   room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic

Solution 4
Use arrow function in the innerFunc(). Arrow functions have special meaning for “this” and it is that, it takes the value of “this” from the enclosing scope and is very useful in this case.

const cleanRoom = function(soap) {   const innerFunc = (_soap)=> {         console.log(`Cleaning ${this.room } with ${_soap}`)         }   innerFunc(soap); }   let harrysRoom = {   room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning Harry’s room with Harpic


Discussion

No Comment Found