SpinSpire logo

`this` keyword

What is the this keyword in JavaScript?

An example of how this works

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

this used globally or outside of function scope

Strict mode

"use strict";
function testFunction() {
return this;
}
// if you run this function the return will
// be undefined

Explicit Functions

Bind

this.x = 9; // 'this' refers to global 'window'
const module = {
x: 81,
getX: function () {
return this.x;
},
};

module.getX();
// returns 81

const retrieveX = module.getX;
retrieveX();
// returns 9; the function gets invoked at the global scope

// Create a new function with 'this' bound to module
// New programmers might confuse the
// global variable 'x' with module's property 'x'
const boundGetX = retrieveX.bind(module);
boundGetX();
// returns 81

Apply()

const array = ["a", "b"];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); //Output: ["a", "b", 0, 1, 2]

Call

function Product(name, price) {
this.name = name;
this.price = price;
}

function Food(name, price) {
Product.call(this, name, price);
this.category = "food";
}

function Toy(name, price) {
Product.call(this, name, price);
this.category = "toy";
}

const cheese = new Food("feta", 5);
const fun = new Toy("robot", 40);

Closing