Actually, this is an old concept only because If you are using ES6 and you don not worry about this. To know more about function binding , check below.
Example Scenario :
Just assume that, you are using setTimeout with object methods or you are trying to passing object methods, then you will loss "this" power.
Means, using this.xxxxx something will give you the result as undefined.
Example code for losing "this":
1 2 3 4 5 6 7 8 | let user = { firstName: "TestName", sayHi() { alert(`Hello, ${this.firstName}!`); } }; setTimeout(user.sayHi, 3000); // Hello, undefined! |
Explanation:
1. We have set 3 seconds for setTimeout function at line no 8.
2. Now sayHi method will be executed and it try to print firstName with the help of this.firstName.
3. As "this" was lost , it will print undefined.
No comments:
Post a Comment