2017-09-15 3 views
2

コードを記述するのが妥当です。関数のプロトタイプ自体をコンストラクタにする

function Base() {} 
Base.prototype = function() { 
    // I am a constructor 
} 
const baseInstance = new Base() 
const secondInstance = new baseInstance() // baseInstance is not a constructor 

私は、コンストラクタに.prototypeの名前のプロパティを作ったが、私は自分のコードで上記のパターンを行うことができるようにしたい場合は、それは非常にシンプルになります理解しています。出来ますか?

答えて

0

私はそれを解決したと思います。それはちょっとしたハックだ。 Object.assign()をコンストラクタにジャムしてください。

function Base() { 
    return Object.assign(
     function SecondConstructor() {}, 
     Base.prototype 
    ) 
} 
Base.prototype = function() { 
    // This can now have properties which 
    // will be attached to the constructor 
} 
const baseInstance = new Base() 
// baseInstance is now a constructor 
const secondInstance = new baseInstance() 

未テストですが、私のコードでは同様の概念を使用しています。

お楽しみください!

関連する問題