How to use “this” in JavaScript

Tomohiro Meo
4 min readJan 18, 2021

Contents

  • The target for this article
  • Four patterns about “this”
  • How to deal with “this” in JavaScript
  • What is should I do when you use “this”?

The Target for this article

  • People who started to study JavaScript recently.
  • People who have experienced another language (ex. Java, Python, Ruby, etc.)
  • People who don’t really know how to use “this” in JavaScript.

Four patterns about “this“ in JavaScript

1. When called with the new operator: Newly created object

The new operator, which is placed before the constructor function when it is called, is not only actually exclusive to constructors in JavaScript, but also can be attached to any function and executed.

What the new operator does is create a new object by copying the prototype object of the function, then pass it to the function as an implicit argument this, and finally, if the function does not end with a return this, it executes it instead.

obj is a new object that does not share an address with dump.prototype

2. When executed as a method: the object to which it belongs

const foo = {
name: 'Foo Object',
dump() {
console.log(this);
},
};
foo.dump(); // { name: 'Foo Object', dump: [Function: dump] }

When executed as a method, its access operator is passed as this.

3. Functions other than 1 and 2 [Non-Strict mode]: Global object

The top-level execution environment in JavaScript is always a global object.
This differs depending on the processor, for example, Node.js has a global object, and a browser has a Window object. So this refers to that global object.

4. Functions other than 1 and 2 [Strict mode]: undefined

This is a mode that disallows some unsafe syntax and functions in the old JavaScript specifications and is enabled by putting ‘use strict’ at the beginning of the file or function.

How to deal with “this” in JavaScript

class Person {
constructor(name) {
this.name = name
}

greet() {
const doIt = function() {
console.log(`Hi, I'm ${this.name}`)
}
doIt()
}
}

const meo = new Person("tomo")
meo.greet() // TypeError: Cannot read property 'name' of undefined

The self in the doIt function only refers to the argument self in the outer scope and has no special meaning. However, since this in JavaScript is implicitly passed on to all functions, doIt will rewrite it as undefined.

Solutions

  • 1. Bind this to a function with bind()
  • 2. Use call() or apply() to specify and execute this
  • 3. Assign the value of this to a temporary variable
  • 4. Define with Arrow function expression
class Person {
constructor(name) {
this.name = name;
}
// Bind this to a function greet1() {
const doIt = function () {
console.log(`Hi, I'm ${this.name}`);
};
const bindedDoIt = doIt.bind(this);
bindedDoIt();
}

// Run with this
greet2() {
const doIt = function () {
console.log(`Hi, I'm ${this.name}`);
};
doIt.call(this);
}
// Transfer the value to the variable this greet3() {
const _this = this;
const doIt = function () {
console.log(`Hi, I'm ${_this.name}`);
};
doIt();
}
// Defined by Arrow function expression greet4() {
const doIt = () => {
console.log(`Hi, I'm ${this.name}`);
};
doIt();
}
// The method itself is also defined by an arrow function expression greet5 = () => {
const doIt = () => {
console.log(`Hi, I'm ${this.name}`);
};
doIt();
}
}
const creamy = new Person('Tomo');
creamy.greet1(); // Hi, I'm Tomo
creamy.greet2(); // Hi, I'm Tomo
creamy.greet3(); // Hi, I'm Tomo
creamy.greet4(); // Hi, I'm Tomo
creamy.greet5(); // Hi, I'm Tomo

What should I do when I use “this”?

  • “This” is only used in class syntax.
  • In the class syntax, all functions, including methods, are defined using arrow function expressions.

Reference Document (Japanese articles and books)

https://oukayuka.booth.pm/items/2368045

--

--