2017-03-11 112 views
1

我简单地试图克隆打字稿中的实例。克隆打字稿中的类实例

jQuery.extend(true, {}, instance)

不起作用,因为方法不复制

任何帮助是极大的赞赏

+0

请定义克隆实例。即使在概念模糊的流行语言如Java中,似乎也没有人会同意它的实际含义。 –

+0

无论如何,尝试'Object.create(instance.prototype)' –

+0

@AluanHaddad thx为您的快速回复,不幸的是这不适用于TS –

回答

3

你可以有一个通用的克隆功能,如果你的类有一个默认的构造函数:

function clone<T>(instance: T): T { 
    const copy = new (instance.constructor as { new(): T })(); 
    Object.assign(copy, instance); 
    return copy; 
} 

例如:

class A { 
    private _num: number; 
    private _str: string; 

    get num() { 
     return this._num; 
    } 

    set num(value: number) { 
     this._num = value; 
    } 

    get str() { 
     return this._str; 
    } 

    set str(value: string) { 
     this._str = value; 
    } 
} 

let a = new A(); 
a.num = 3; 
a.str = "string"; 

let b = clone(a); 
console.log(b.num); // 3 
console.log(b.str); // "string" 

code in playground

如果你的等级比较复杂(有其他类的实例成员和/或不具有默认的构造函数),然后在你的类添加一个clone方法,知道如何构建和赋值。

+0

感谢您的回答至关重要。在这种情况下,我需要确保我从不使用构造函数,而是使用工厂和设置器?欢呼声 –

+0

好吧,然后导出工厂函数和克隆函数,但不要导出类本身 –