概要
奇妙なコードを書けたので紹介します。
['constructor']['constructor']['constructor']('return this')()['console']['log']('Hello JavaScript!')
// > Hello JavaScript!
unsafe-eval がOFF、 strict でない環境でしか動作しません。
説明
['constructor']
// Array: ['constructor']
要素が 'constructor' の配列のリテラルです。
['constructor']['constructor']
// Array()
配列の constructor プロパティを参照します。配列オブジェクトのコンストラクタは Array オブジェクトです。
['constructor']['constructor']['constructor']
// Function()
Array オブジェクトの constructor プロパティを参照します。関数のコンストラクタは Function オブジェクトです。
['constructor']['constructor']['constructor']('return this')
// function() { return this; }
Function() の引数に文字列を渡すと、その文字列を実行する関数を生成します ((code) => eval(code) のようなものです)。
['constructor']['constructor']['constructor']('return this')()
// window
非 strict モードの場合、 global コンテキストで this は globalThis を指します。ブラウザ環境では window です。
['constructor']['constructor']['constructor']('return this')()['console']['log']
// window.console.log
window.console.log を参照します。
['constructor']['constructor']['constructor']('return this')()['console']['log']('Hello JavaScript!')
console.log('Hello JavaScript!') と等価です。