简体   繁体   English

如何在Typescript中合并类实例?

[英]How to merge class instances in Typescript?

I have a class like this: 我有一个这样的课:

class Person {
    private _age: number;

    get age(): number {
        return this._age;
    }

    set age(value: number) {
        this._age = value;
    }
}

And an instance of that class: 并且该类的一个实例:

let peter = new Person();
peter.age = 30;

I want to have another instance of that class by simply using the spread operator: 我希望通过简单地使用spread运算符来获得该类的另一个实例:

let marc = {
    ...peter,
    age: 20
}

But this does not result in an instance of Person but in an object without the getter and setter of Person . 但是这不会导致Person的实例,而是在没有Person的getter和setter的对象中。

Is it possible to merge class instances somehow or do I need to use new Person() again for mark ? 是否有可能以某种方式合并类实例,或者我是否需要再次使用new Person()mark

Spread syntax is supposed to produce plain object, so it isn't applicable. Spread语法应该生成普通对象,因此不适用。 If new class instance is needed, it should be created with new . 如果需要新的类实例,则应使用new创建它。 If an object has to be merged with other properties, Object.assign can be used: 如果必须将对象与其他属性合并,则可以使用Object.assign

let marc = Object.assign(
    new Person()
    peter,
    { age: 20 }
);

Since Object.assign processes own enumerable properties, the result may be undesirable or unexpected, depending on class internals; 由于Object.assign处理拥有可枚举的属性,因此结果可能是不合需要的或意外的,具体取决于类内部; it will copy private _age but not public age from peter . 它会复制私人_age但不会复制peter公共age

In any special case a class should implement utility methods like clone that is aware of class internals and creates an instance properly. 在任何特殊情况下,类都应该实现实用方法,例如知道类内部的clone并正确创建实例。

In OOP terms you don't define your properties after creating instances, you define them in your class 在OOP术语中,您不会在创建实例后定义属性,而是在class定义它们

In your example both Marc and Peter have an age so you don't need to merge anything. 在你的例子中,Marc和Peter都有一个年龄,所以你不需要合并任何东西。 You could use the contructor to pass a specific value for that instance: 您可以使用构造函数为该实例传递特定值:

let marc = new Person("marc", 20)
let peter = new Person("peter", 30)

class Person {
    constructor(private name:string, private age:number){
       console.log("I am " + this.name + " my age is " + this.age)
    }
}

If there is a property that no person except Marc has, then you can let Marc extend Person. 如果有一个属性,除了Marc之外没有人,那么你可以让Marc延长Person。

class Person {

}

class Marc extends Person {
    car:string
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM