javascript メソッドを短縮して利用する

javascript メソッドを短縮して利用する

javascriptで、コード内で使用頻度の高いメソッドやオブジェクトを変数に代入してコードを短縮して利用する手順を記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.66

メソッド短縮

メソッドを変数に代入しておくと、短縮して記述することが可能です。

let c = console.log;

c("hello"); // hello
c("world"); // world

「Math.floor」にも使用してみます。

let c = console.log;
let m = Math.floor;

c((1.23)); // 1
c(m(-1.23)); // -2

となります。

ただし、ネイティブ関数の場合はエラーとなってしまいます。

let w = document.write;
w("hello"); // Uncaught TypeError: Illegal invocation

chromeのエラーメッセージ

firefox102のエラーメッセージ

ncaught TypeError: 'write' called on an object that does not implement interface Document.

ネイティブ関数は、直接参照できないようなため、以下のようにしてラップして使用します。

const w = hoge => document.write(hoge);
w("hello");