Let's say you have a ultra complex 🤣 getUser() function which prints the value of this object in console.
The value of this will change on basis how the function is being invoked with respect to the context.
function getUser() {
console.log(this);
}
1. Calling a function with name.
/** "this" holds window object. **/
getUsers();
2. Calling a function with object property.
let someObject = {
getUsers: getUsers
};
/** "this" will be someObject:{} **/
someObject.getUsers();
3. Calling a function with call, bind & apply methods.
let someObject = {
name: "Suraj"
};
/** "this" will be someObject:{...} **/
getUsers.call(someObject);
4. Calling a function with new keyword.
/** "this" will be getUsers {} object **/
new getUsers();
That's was a short explanation on this creation i know 😃 but that is all you may need to know about this creation for now.
In next blog we'll deep dive into the usage of this.
Top comments (0)