私たちはES6とimmutable.jsを使用して、不変のクラスを作成します。ImmutableJSレコードを使用して異なる属性を持つサブクラスを作成
class Animal extends Record({foo: ""});
どのように私は動物から継承し、カスタムプロパティを追加し、まだ不変Record
としてそれを使用することができますか?
class Animal extends Animal {}; // How to add the key "bar"?
私たちはES6とimmutable.jsを使用して、不変のクラスを作成します。ImmutableJSレコードを使用して異なる属性を持つサブクラスを作成
class Animal extends Record({foo: ""});
どのように私は動物から継承し、カスタムプロパティを追加し、まだ不変Record
としてそれを使用することができますか?
class Animal extends Animal {}; // How to add the key "bar"?
Record
方法はdefaultValues
に作成された型をロックし、それ以上の特性を拡張するために使用することができません。これは私が言及したグリップの一つですhere。
あなたは、実行時に継承を確認するにあまりにも曲がっていない場合(instanceof
)、その後、あなたがこれを行うことができますが -
let foo = {foo: ""};
class Animal extends Immutable.Record(foo){}
let bar = {bar: ""};
class Mammals extends Immutable.Record(Object.assign({}, foo, bar)){}
、それはあなたがスキーマを少し再利用する真の継承の代替できませんが。メソッドはこのように継承されません。
ここではミックスインを使用できます。
const PersonMixin = Base => class extends Base {
grew(years) {
return this.set("age", this.age + years); //returns a new Person, which is fine
}
};
const PersonBase = PersonMixin(new Immutable.Record({name: null, age: null}));
class Person extends PersonBase {}
const AcademicanBase = PersonMixin(new Immutable.Record({name: null, age: null, title: null}));
class Academician extends AcademicanBase {
constructor({name, age, title}) {
super({name, age, title});
}
}
var a = new Academician({name: "Bob", age: 50, title: "Assoc. Prof"});
console.log(a);
console.log(a.grew(10).age); //grew works
a.title = "Prof"; //the error "Cannot set on an immutable record" received.
私はそうは考えません。 –
はい、不可能です:https://github.com/facebook/immutable-js/issues/334。 –