let name = {
firstName: "Ankur",
lastName: "Kashyap",
printFullName: function() {
console.log(this.firstName + " " + this.lastName);
}
};
const { printFullName, firstName, lastName } = name;
console.log(firstName + " " + lastName);
printFullName();
In the above code, we de-structured the printFullName() function from 'name' object and called the function. On calling printFullName() function, it gives the value of this.firstName and this.lastName to be undefined undefined.
Although we have also de-structured the firstName and the lastName from the 'name' object, and we can see the value in the console. But in case of printFullName() function, we see undefined undefined.
So, why printFullName() function is not working as expected?
Let's see why it is behaving like this:
When we de-structure a method printFullName() from an object and assign it to a new constant, it loses its original context. As a result of which when we later invoke printFullName() function, the 'this' keyword no longer points to the object 'name' and this.firstName and this.lastName becomes 'undefined'.
To resolve this issue we can use 'bind' method which explicitly binds the printFullName() function to the 'name' object.
let name = {
firstName: "Ankur",
lastName: "Kashyap",
printFullName: function() {
console.log(this.firstName + " " + this.lastName);
}
};
const { printFullName, firstName, lastName } = name;
const bindPrintFullName = printFullName.bind(name);
bindPrintFullName();
'bind' method ensures that the 'this' inside the printFullName() function refers to the 'name' object.
More topics:
Debouncing in JavaScript: kashyap171ankur.com/debouncing-in-javascript