LoginSignup
4

More than 5 years have passed since last update.

class構文で関数を作るクラスを定義

Last updated at Posted at 2016-05-17

二つの方法があります。

  1. コンストラクタで関数を生成する
  2. Functionコンストラクタを継承する

Chrome 50.0.2661.102とNode v6.1.0で確認しました。

コンストラクタで関数を生成

class構文のcontstructorはreturn文で、生成するオブジェクトを上書きできます。

Overriding the result of a constructor

Just like in ES5, you can override the result of a constructor by explicitly returning an object:

class Foo {
    constructor() {
        return Object.create(null);
    }
}
console.log(new Foo() instanceof Foo); // false

If you do so, it doesn’t matter whether this has been initialized or not. In other words: you don’t have to call super() in a derived constructor if you override the result in this manner.

関数を生成してreturnすれば、関数を返すクラスを定義できます。

class Hoge {
  constructor() {
    return function(val){
      console.log(val)
    }
  }
}
new Hoge()('hi')

継承

setPrototypeOfを使って、prototypeを設定します。

class Fuga {
  hi(){ console.log('hi') }
}
class Hoge {
  constructor() {
    function log(val){
      console.log(val)
    }
    Object.setPrototypeOf(log, new Fuga)

    return log
  }
}
new Hoge().hi()

感想

class Fuga {
  hi(){ console.log('hi') }
}
function Hoge
  console.log(val)
}
Object.setPrototypeOf(Hoge, new Fuga)

の方が、良いのでは?という気持ちになります。

Functionコンストラクタを継承

Functionを継承して、superでFunctionコンストラクタを呼び出すと、関数をつくれます。

class Hoge extends Function {
  constructor() {
    super('val', 'console.log(val)')
  }
}

継承

class Fuga extends Function {
  hi(){ console.log('hi') }
}
class Hoge extends Fuga{
  constructor() {
    super('val', 'console.log(val)')
  }
}

感想

Functionコンストラクタを使うことに、なぜか恐怖を覚えます。

おまけ

FunctionコンストラクタはSpread operatorも使える

new Function('...rest', 'console.log(...rest)')

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