LoginSignup
8
7

More than 5 years have passed since last update.

CoffeeScriptとかJavascriptとかで、省力化とかに使えるメソッドのエイリアスを作る

Last updated at Posted at 2015-06-10

こーゆーの、すき

console.log を短く書くために(IE8+ 対応)という記事がQiitaにあって、大変面白かったので、下記みたいに一般化してみた。で、あー、こーゆーのすきー、って感じでゆるりと見ていた。まあ、たいていの場合bindで済むんだろうけど、Mathなんかも嘘メソッドの実装ありそうだしな。「?nternet ?xplorer 6」とかな。冤罪だったらごめん。でも、そーゆー可能性は少なくないので、リンク先で学んだ書き方は、大変安心感がある。あ、でも、ログ以外の時は、空の関数返しちゃいかん気もするな……。まあしかし、rootとかroot.methodとかが存在しないって、それは嘘過ぎるだろ。と無責任に締めていたのだが、ちょっと反省した。まあ、consoleじゃない時は、TypeError例外投げとこう。っとおもってちょっと書いたが、考えてみたら、rootが未定義だったらそれが何を意図して渡されたのか、分かんないや。丁寧にやりたい人は、rootも文字列で引き渡して、evalで評価して下さい。で、それならconsoleを意図していて未定義なら空の関数を返し、そうでないならTypeErrorで綺麗ですね。私はやらないです。ログに警告くらいです。

まあ、そういう危険なものだとしても、タイプ数減らすのには貢献するし、「alias」と名付けておくと可読性も上がるので、これで良いかな、と思う。

alias = ((root,method) ->
  if not (root?[method]?)
    console.warn 'alias is danger!'
    return ->
  if not (root[method].bind?)
    return -> Function.prototype.apply.call(root[method], root, arguments)
  root[method].bind(root)
)

log = alias(console,'log')
fl = alias(Math,'floor')

log fl 5.23
8
7
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
8
7