Cloning a TypeScript Object

前端 未结 4 2392
眼角桃花
眼角桃花 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:09

    If you're using TS 2.1, you can use object spread operator to create a shallow copy:

    const obj = { a: 1 };
    const clonedObj = { ...obj };
    
    0 讨论(0)
  • 2021-02-20 06:11

    .clone() only clones DOM elements. In order to clone JavaScript objects try jQuery.extend. Something like this

    // Shallow copy
    var newObject = jQuery.extend({}, oldObject);
    
    // Deep copy
    var newObject = jQuery.extend(true, {}, oldObject);
    

    Typescript transpiles to JavaScript. So, JavaScript way will work fine.

    Demo:

    // Transpiled version of TypeScript
    "use strict";
        var Restaurant = (function () {
            function Restaurant(id, name) {
                this.id = id;
                this.name = name;
            }
            Restaurant.prototype.getId = function () {
                return this.id;
            };
            Restaurant.prototype.setId = function (_id) {
                this.id = _id;
            };
            Restaurant.prototype.getName = function () {
                return this.name;
            };
            Restaurant.prototype.setName = function (_name) {
                this.name = _name;
            };
            return Restaurant;
        }());
    
    // Test Snippet
    var r1 = new Restaurant(1, "A");
    var r2 = jQuery.extend(true, {}, r1);
    
    r2.setName("B");
    
    console.log(r1.name);
    console.log(r2.name);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2021-02-20 06:15
    • Using standard ES6 features

      const clone = Object.assign({}, myObject)
      

      Warning: this performs a shallow clone.

      This excellent page from MDN contains tons of details on cloning, including a polyfill for ES5

    • A "quick" way of deep cloning is to use JSON utilities

      const clone = JSON.parse(JSON.stringify(myObject))
      
    • A "proper" way of cloning is to implement a clone method or a copy constructor...

    I know, I know, not enough JQuery

    0 讨论(0)
  • 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);
            }
        }
    
    0 讨论(0)
提交回复
热议问题