JavaScript thisについてpart2

20220331

JavaScript

t f B! P L

 プログラミング

this

part1からのつづき。
GoogleConsoleのデバッグコンソールで以下を実行してみる。

const Person = function (name) { this.name = name; return this; };
Person('somebody'); //Window {0: Window, window: Window, self: Window, document: document, name: 'somebody', location: Location, …}

グローバルオブジェクトのnameプロパティをsomebodyに変更してしまった!
strictモードだと、

const Person = function (name) { 'use strict'; this.name = name; return this; };
Person('somebody'); //Uncaught TypeError: Cannot set properties of undefined (setting 'name')
    at Person (<anonymous>:1:58)
    at <anonymous>:2:1

thisにundefinedが入り、グローバルオブジェクトは変更できなくなっている。

よって、クラス構文内はstrictモードで実行されるため、thisにundefinedが入る場合がある。

class Person {
 constructor(name) {
  this.name = name;
 }
 greet() {
  const doIt = function () {
   console.log(`こんにちは、 ${this.name}です。`);
  };
  doIt();
 }
}
const aichan = new Person('Aichan');
aichan.greet(); // TypeError: Cannot read property 'name' of undefined

doItのthisはundefinedになってしまう。
この場合どうしたらよいか?

アロー関数式を推奨

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

 greet = () => { 
  const doIt = () => {
   console.log(`こんにちは、 ${this.name}です。`);
 };
 doIt();
 }
}
const aichan = new Person('Aichan');
aichan.greet(); // こんにちは、 Aichanです。

アロー関数は暗黙の引数としての
this を持たず、this を参照すると関数の外のスコープの this の値がそのまま使われる

よって、
・thisはクラス構文内だけで使うようにする。
・クラス構文内のメソッドは、アロー関数式で定義する。
というルールが良い。

このブログについて

技術的に悩んだこと、やってみたことを書き溜めています。自身の復習のため、また同じ悩みがある方は参考にできるような書き方にしていきます。 趣味の競馬AI開発と競馬AIでの予想も公開していきます。 金曜日に土曜日の中央競馬(JRA)全レース予想、土曜日に日曜日の中央競馬(JRA)全レース予想を公開する予定です。

Tags

Golang (1) JavaScript (9) python (2) 機械学習 (6) 競馬 (343) 副業 (2)

注目の投稿

2023/06/04(日) 競馬AI予想(東京競馬場)

このブログを検索

アーカイブ

投稿者情報

TANDE競馬のあいちゃんのアイコンです

はじめまして。あいちゃんです。雑魚エンジニアです。趣味で機械学習をやっています。日々の勉強としてアウトプットしていきます。

QooQ