Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 强制子类不可变_Javascript_Oop_Typescript_Design Patterns_Immutable.js - Fatal编程技术网

Javascript 强制子类不可变

Javascript 强制子类不可变,javascript,oop,typescript,design-patterns,immutable.js,Javascript,Oop,Typescript,Design Patterns,Immutable.js,我有一个具有一些属性的基类: class Component { readonly id: number readonly type: number } 我想要一些子类: class HealthComponent extends Component { max_health: number, current_health: number } etc. 我想要的本质是使HealthComponent具有与不可变组件相同的行为。Record: const he

我有一个具有一些属性的基类:

class Component {
    readonly id: number
    readonly type: number
}
我想要一些子类:

class HealthComponent extends Component {
    max_health: number,
    current_health: number
}

etc.
我想要的本质是使
HealthComponent
具有与
不可变组件相同的行为。Record

const health = HealthComponent(100, 100);
health.max_health = 40; // Shouldn't work
const new_health = new HealthComponent(40, health.current_health); // Works
所有的类都只是数据;没有行为(如果有任何行为,它将在静态方法中,而不是在实例方法中)。现在我想尽可能地强制子类是不可变的(在这个意义上,允许修改,但进行更改会导致新对象或抛出一个错误a la immutable.js),我无法找到最好的方法来做到这一点

t我想到的最好的办法是让每个子类都有一个只读的
数据
成员,它是一个
不可变的。用适当的字段记录
,但即使这样也不太正确,因为更改它会返回一个新的
数据
对象,但我真的想要一个全新的
组件
对象,这也不能强制所有组件都遵循这个约定

我考虑过的另一件事是让基类是一个
不可变的。使用
data:Immutable.Map
字段记录
,然后子类提供一个
不可变的。将
映射到
超级
构造函数,并使用所有键,但是人们可以随意添加新键,这也不理想


这里有没有一种神奇的设计模式可以帮助我?

使用
只读


那是一段相当难理解的段落。通常最好将段落限制在2-3句,然后是一个新段落(在合理范围内)。
class Component {
    constructor(public id: number, public type: number) {

    }
}

class HealthComponent extends Component {
    constructor(public id: number, public type: number, public max_health: number, public current_health: number) {
        super(id, type);
     }
}

let hc: Readonly<HealthComponent> = new HealthComponent(1, 2, 3, 4);
hc.max_health = 40; // Error
interface Component {
    id: number
    type: number
}

interface HealthComponent extends Component {
    max_health: number;
    current_health: number;
}

let hc: Readonly<HealthComponent> = {
    id: 1,
    type: 2,
    max_health: 3,
    current_health: 4
};

hc.max_health = 40; // Error