this keyword
What is the this keyword in JavaScript?
- The JavaScript
thiskeyword refers to an object it belongs to. thisby itself refers to the global object and inside of a functionthisis undefined.- Inside of event handlers and functions the
thiskeyword refers to whatever element received the event. - A function’s
thiskeyword behaves differently in JS than in other programming languages. - Introduced in ES2015 you can now call the
bind()method to set the value ofthisinside a function regardless of how the function is being called. - Arrow functions don’t provide their own
thisbinding.
Example
const testObj = {
item: "hamburger",
count: 20,
inventory: function () {
return `we have ${this.count} ${this.item}'s`;
},
};
console.log(testObj.inventory());
// output: we have 20 hamburgers
Inside an object, this refers to the owner of the method.
Strict mode
JS strict mode does not allow default binding:
"use strict";
function testFunction() {
return this;
}
// if you run this function the return will be undefined
Explicit Functions
bind()
bind() creates a new function with the same body and scope as “t”, however the new function will be bound to the first argument of bind regardless of how the function is being used.
const boundGetX = retrieveX.bind(module);
boundGetX();
// returns 81
apply()
Apply calls a function that takes arguments as an array or array-like objects.
call()
Takes a “this” object argument and any number of arguments. Allows a function/object method to be assigned and called to a different object.