LoginSignup
2
3

More than 5 years have passed since last update.

せっかくなのでjsのthisについて超ざっくりとメモとサンプルコード

Posted at
// jsのthisは、関数自身が所属しているオブジェクトへの参照
// jsのthisは、関数自身が所属しているオブジェクトがない場合は、windowへの参照になる
// allow関数のthisは定義された関数内のthisへの参照を持つ

const a = {
    hoge() {
        function fuga() {
            console.log(3, this) // 3 Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
        }
        console.log(2, this) // 2 {hoge: ƒ}
        console.log(fuga())
    }
}
console.log(1, a) // 1 {hoge: ƒ}
a.hoge()

function b() {
    console.log('b', this)
    const fuga = () => this
    console.log('allow', fuga())
    // 'allow'と'b'のthisは同じ
}
b() // b Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
const c = { b }
console.log(c) // {b: ƒ}
c.b() // b {b: ƒ}

const d = () => {
    console.log('d', this) // d Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
}
d()
const e = { d }
console.log(e) // {d: ƒ}
e.d() // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
2
3
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
2
3