関数の復習:callback関数について理解する

用語集

基礎知識

thisは今のスコープのオブジェクト自体を指します

// A:
obj = {
  name: "松田信介",
  hello: function () {
    console.log(name)
  }
}

console.log(obj.name)

// B:
obj = {
  **name: "松田信介",**
  hello: function () {
    console.log(this.name)
  }
}

省略記法もあります

obj = {
  **name: "松田信介",**
  hello () {
    console.log(this.name + "さん、こんにちは")
  },
  goodbye () {
    console.log(this.name + "さん、こんばんは")
  }
}

試してみよう

オブエジェクトの中にいない場合は、globalにいる・・・??

var hoge = "hogehoge"

console.log(hoge)
// "hogehoge"
console.log(this.hoge)
// "hogehoge"
console.log(window.hoge)
// "hogehoge"

this === globalThis // true
this === window     // true

thisが必要な理由

this がないとグローバル変数を参照してしまう

var obj = {
  name: "松田",
  birthday: "1985/04/13",
  hello: function(){
		console.log(name + birthday) 
    // console.log(this.name + " " + this.birthday)
  }
}

思ったように動かない・・・?

var obj = {
  name: "松田",
  birthday: "1985/04/13",
  hello: function(){
    console.log(this.name + " " + this.birthday)
  },
 ** IntervalHello: function(){
    window.setInterval(this.hello, 1000)
  }
}

思ったように動く・・・?

var obj = {
  name: "松田",
  birthday: "1985/04/13",
  hello: function(){
    console.log(this.name + " " + this.birthday)
  },
  IntervalHello: function(){
    window.setInterval(() => { this.hello() }, 1000)
  }
}

グローバル関数をプロパティにセットしてみると・・・?