LoginSignup
4

More than 1 year has passed since last update.

奇妙なJavaScript

Last updated at Posted at 2022-07-07

概要

奇妙なコードを書けたので紹介します。

['constructor']['constructor']['constructor']('return this')()['console']['log']('Hello JavaScript!')
// > Hello JavaScript!

unsafe-eval がOFF、 static でない環境でしか動作しません。

説明

['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

static モードの場合、 global コンテキストで this はグローバルオブジェクトを指します。ブラウザ環境では 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!') と等価です。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4