6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

どうしても無名関数だと困る場合

Last updated at Posted at 2012-02-02

CoffeeScriptで関数を定義すると必ず無名関数で定義される

hoge = ->
var hoge;

hoge = function () {};

基本的にこれで問題ないけど、無名関数だと困る場合がたまにある。具体的にはコンストラクタの名前にアクセスしたい場合。

hoge = function() {};
h = new hoge();
h.constructor.name // => ""

function hoge() {}
h = new hoge();
h.constructor.name // => "hoge"

このような場面で無名関数でなく有名関数(?)を強制的に使いたい場合もclassを使えばできる。というか、コンストラクタとして使うのだからclassを使えというのは、至極当たり前な感じもする。

class hoge
h = new hoge
console.log h.constructor.name
hoge = (function() {

  function hoge() {}

  return hoge;

})();

h = new hoge();
console.log(h.constructor.name) // => "hoge"

さらに余談で、何故僕がこんな重箱の隅の問題にはまったかというと、gjstestというjsのテストフレームワークを使おうとして、コンストラクタの名前が空だと、結果をhtmlに出力した時にバグが生じるためでした。

6
6
2

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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?