ES6クラスで簡単なORMを作成すると、ブロック問題が発生します。クラスを正しくコピーできません(ES5ではutil.extend
と同じです)。ES6クラスのオブジェクトコンストラクタをクローンする方法は?
具体的には、ここで私が試したものです:
class BaseModel {
echo() {
console.log(this.props);
}
static _setProperties(props) {
this.props = props;
}
}
function makeModel(props) {
// Try to copy the Class object
const Model =
Object.assign(Object.create(Object.getPrototypeOf(BaseModel)), BaseModel);
// Copy my static methods – is there a better way to do this?
Object.getOwnPropertyNames(BaseModel).forEach((key) => {
if (!key.startsWith('_')) return;
Model[key] = BaseModel[key];
});
// Configure the new model
Model._setProperties(props);
return Model;
}
const GreeterModel = makeModel('hello');
const greeter = new GreeterModel();
greeter.echo(); // Should log hello
私が手にエラーがある:
TypeError: GreeterModel is not a constructor
はES6クラスでこれを達成する方法はありますか、私はに固執する必要がありますES5スタイル?
オプションの質問:静的メソッドをコピーするより良い方法はありますか? getOwnPropertyNames
のソリューションは、length
のような読み取り専用のプロパティも返すので理想的ではありません。
ありがとうございます!
'Object.create'は関数を作成しません。このコードはES5でも機能しません。 – Bergi
なぜES6 'class extends'を使うのではないのですか? – Bergi