Cloning a TypeScript Object

前端 未结 4 2361
眼角桃花
眼角桃花 2021-02-20 05:58

I have a typescript class

export class Restaurant {

  constructor ( private id: string, private name: string ) {

  }

  public getId() : string {
    return th         


        
4条回答
  •  情歌与酒
    2021-02-20 06:21

    This seems to work for me:

    var newObject = Object.assign(Object.create(oldObj), oldObj)
    

    Object.create creates a new instance with empty properties Object.assign then takes that new instance and assigns the properties

    A more robust version of a clone function

        clone(obj) {
            if(Array.isArray(obj)) {
                return Array.from(obj);
            } else {
                return Object.assign(Object.create(obj), obj);
            }
        }
    

提交回复
热议问题