LoginSignup
0
1

More than 3 years have passed since last update.

「JavaScript の this を理解する多分一番分かりやすい説明」を読んで手を動かして理解した

Last updated at Posted at 2020-02-16

JavaScript の this を理解する多分一番分かりやすい説明を読んで手を動かしてみた。

サンプルコード

function test() {
    console.log(this)
}
var obj = {}
obj.test = test

console.log(test) //1
console.log(obj)  //2
test() //3
obj.test() //4

1

関数そのものを出力。

ƒ test() {
    console.log(this)
    }

2

関数そのものが入っているオブジェクトを出力。

{test: ƒ}

3

thisはグローバルオブジェクト、ブラウザではWindowオブジェクトをさす。

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

4

thisはobj(関数そのものが入っているオブジェクト)をさす。

{test: ƒ}

メソッドチェーン


var obj = {
    test: function() { return this },
    alert: function(msg) { console.log(msg) }
    }
var test = obj.test

console.log(test) // 1
console.log(obj.test()) // 2
console.log(test()) // 3
test() // 4
obj.test().alert("hello") // 5
test().alert("hello") // 6

1

オブジェクトの中身のtestそのものを出力。

ƒ () { return this }

2

thisはobjをさすことを出力。

{test: ƒ, alert: ƒ}

3

thisはグローバルオブジェクト、ブラウザではWindowオブジェクトをさすことを出力。

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

4

関数名ではないため呼び出せない。

5

オブジェクトの中身のalertを発動

hello

6

Windowオブジェクトに対してalertを発動

helloというアラートを表示

理解が深まる記事

JavaScript中級者への道【2. 4種類のthis】

0
1
0

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
1