メソッドでもアロー関数でもない関数内のthis
は下記の点でブラウザもNode.jsも同じ。
strict
モードではundefined
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>関数内のthis</title>
<script>
// モードによらず、
// ブラウザのトップレベルのthisはグローバルオブジェクト。
console.log(this === window) // true
strictモード() // 推奨
ゆるいモード()
function strictモード(){
'use strict'
console.log(this === undefined) // true
}
function ゆるいモード(){
// ゆるいと関数内thisはグローバルオブジェクト。
console.log(this === window) // true
}
</script>
</head>
<body>
</body>
</html>
#!/usr/bin/env node
// モードによらず、
// Node.jsのトップレベルのthisはグローバルオブジェクトではない。
console.log(console === global.console, this !== global) // true true
console.log(this === module.exports) // true
strictモード()
ゆるいモード()
function strictモード() {
'use strict'
console.log(this === undefined) // true
}
function ゆるいモード() {
// ゆるいと関数内thisはグローバルオブジェクト。
console.log(this === global) // true
}