callやapplyメソッド経由でのthis

callapplyメソッドで関数内thisのオブジェクトを指定できる(アロー関数を除く)。なお、strictモードでなく、かつ、指定がなぜかundefinednullだと、thisはグローバルオブジェクトになる。

#!/usr/bin/env node

function strictな関数() {
  'use strict'
  console.log(this.名前)
}

function ゆるい関数() {
  // ブラウザではwindow、Node.jsではglobal。
  const グローバルオブジェクト = typeof window === 'object' ? window : global
  console.log(this === グローバルオブジェクト)
}

// strictモードでは関数内thisがundefinedなのでエラー。
// strictな関数() // TypeError: Cannot read property '名前' of undefined

const アリス = {
  名前: 'アリス'
}
// callやapplyでthisを変更できる。
strictな関数.call(アリス) // アリス


// callにnullやundefinedを指定したとき、strictモードでなければ、
// thisはグローバルオブジェクトを指す。
ゆるい関数.call(undefined) // true
ゆるい関数.call(null) // true