call
やapply
メソッドで関数内this
のオブジェクトを指定できる(アロー関数を除く)。なお、strict
モードでなく、かつ、指定がなぜかundefined
かnull
だと、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