LoginSignup
21
10

More than 3 years have passed since last update.

JavaScript、許されざる呪文

Last updated at Posted at 2019-12-11

初めに

ノリと勢いでこの記事を書いているので、突っ込みどころも多いかと思いますが温かい目で読んでください。
闇の魔術に対する防衛術 Advent Calendar 2019 | 12日目の記事です。

許されざる呪文

取り敢えず、許されざる呪文を唱えてみる。

crucio.js
document.write = "Crucio";
console.log(document.write); //Crucio

ただ、コンソールにCrucioを出力しているだけの単純なコードである。
だが、Crucioを代入している変数名に大きな問題がある。
そもそも、document.writeはjavaScriptで標準的に備わっている関数である。

変数を代入した後に関数を使用してみたい!

crucio.js
document.write = "Crucio";
console.log(document.write); //Crucio
document.write("Crucio"); //Uncaught TypeError: document.write is not a function

当然のエラーメッセージ

関数にユーザー定義関数を代入してみる

crucio.js
function hoge(text) {
    console.log(text);
}
document.write = hoge;
document.write("Crucio"); //Crucio

はい。上手くいきました。

console.logをdocument.writeで書きたい!

crucio.js
document.write = console.log;
document.write("Crucio"); //Crucio

まぁ、通っちゃいますよね^^;

関数の中身を出力したい!

crucio.js
function hoge(text) {
    console.log(text);
}
console.log(hoge);
/* f hoge(text){
 *    console.log(text);
 * }
 * /

別の闇の魔術ですがjavaScriptではこの様にユーザー定義関数であれば関数内のコードを出力することが出来ます。

crucio.js
console.log(console.log);
/* ƒ log() { [native code] } */

但し、デフォルトの関数は無理。
※本来どちらも出来ないようにしておくべきだとは思います...。

じゃあ、これなら?

crucio.js
function hoge(text) {
    console.log(text);
}
document.write = hoge;
console.log(document.write);
/* f hoge(text){
 *    console.log(text);
 * }
 * /

あ、出るじゃん。ちゃっかり上書きされてる。

最後に

この仕様を活用することが出来る闇の魔法使いは駆逐されてしかるべきだろう。

何故この様な挙動が起きてしまっているかはjSの独特な型に由来するものなので興味が出たり額の傷が疼いた方は是非、調べてみるといい勉強になると思う。

決して書くのが面倒だったとかそういう事を言ってはならない

21
10
0

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
21
10