我们使用ES6和immutable.js来创建不可变的类。
1 2
3 4
如何从Animal继承并添加自定义属性,但仍然可以将其用作不可变class Animal extends Record({foo: ""});
?
Record
答案 0 :(得分:2)
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)){}
虽然不能替代真正的继承,但它可以让您重复使用模式。方法不会以这种方式继承。
答案 1 :(得分:1)
我们可以在这里使用mixins。
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.
答案 2 :(得分:1)
我已经结束了,希望对您有所帮助。
// @flow
import type {RecordFactory, RecordOf} from "immutable";
import {Record} from "immutable";
type OneProps = {|
key: boolean
|};
const oneDefaults: OneProps = {
key: false
};
type One = RecordOf<OneProps>;
const oneItemBuilder: RecordFactory<OneProps> = Record(oneDefaults);
type TwoProps = {|
...OneProps,
moreKeys: string
|};
const twoDefaults: TwoProps = {
...oneDefaults,
moreKeys: "more"
};
type Two = RecordOf<TwoProps>;
const twoItemBuilder: RecordFactory<TwoProps> = Record(twoDefaults);
const oneItem: One = oneItemBuilder();
const twoItem: Two = twoItemBuilder({moreKeys: "more keys"});