LoginSignup
0
0

thisについて

Posted at

はじめに

jsでthisのことをよくわかっていなかったので、

試してみた

.js
const movie = {
    name: 'コナン',
    kind: 'アニメ',
    genre: 'ミステリー',
    location: '日本',
    introduction() {
        console.log(`${name}}です`);
    }
}

コンソールでintroductionメソッドを呼び出すと以下のようにnameが表示されない

image.png

thisを使って呼び出す

.js
const movie = {
    name: 'コナン',
    kind: 'アニメ',
    genre: 'ミステリー',
    introduction() {
        console.log(`${this.name}です`);
    }
}

名前が表示された!
this.nameとすることでオブジェクトに入っている変数が使える
image.png

thisの値は、thisを使っている関数がどのように呼ばれたかで決まる

.js
// introdutionを別の変数に入れてみた
const movie2 = movie.introduction;

image.png

何が入っているのかわからないので、ログを入れてみた
movieのthisにはオブジェクト
movie2のthisにはwindowが入っている
image.png

windowが何者なのか・・・?
windowというのはjavascriptに必ず存在しており、
あらゆるものがwindowに存在している
ということだけはわかったので今のところ深入りはしない
https://developer.mozilla.org/ja/docs/Web/API/Window

まとめ

thisはどこで呼ばれるかどうかで入ってくる値が変わる
this.movieの場合はそのオブジェクトがthisになる
.xxxxとかの場合は、windowが入ってくる

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0