Javascript 克隆一个 TypeScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39833288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:56:42  来源:igfitidea点击:

Cloning a TypeScript Object

javascripttypescriptclone

提问by mwild

I have a typescript class

我有一个打字稿班

export class Restaurant {

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

  }

  public getId() : string {
    return this.id;
  }

  public setId(_id : string) {
    this.id = _id;
  }

  public getName () {
    return this.name;
  }

  public setName ( _name:string ) {
    this.name = _name;
  }

}

I then have an instance of this class ( this is an example ):

然后我有一个这个类的实例(这是一个例子):

restaurant:Restaurant = new Restaurant(1,"TestRest");

I then store this restaurant object in some sort of cache

然后我将这个餐厅对象存储在某种缓存中

cache.store( restaurant );

then later in my application I get the restaurant back

然后在我的申请中,我把餐厅拿回来了

var restToEdit = cache.get( "1" );
restToEdit.setName( "NewName" );

But because of javascripts pass by reference on objects, the changes I make to restToEdit also get saved in the restaurant that is in the cache.

但是由于 javascripts 通过对象的引用传递,我对 restToEdit 所做的更改也保存在缓存中的餐厅中。

I basically want the restaurant in the cache to be a totally different instance to the restToEdit.

我基本上希望缓存中的餐厅与 restToEdit 完全不同。

I have tried using jQuery.clone and extend, but it doesn't seem to work and I think this is because of it being a typescript object. Or will that not matter?

我曾尝试使用 jQuery.clone 和扩展,但它似乎不起作用,我认为这是因为它是一个打字稿对象。或者那没关系?

Any answers on how to clone this object would be appreciated

任何有关如何克隆此对象的答案将不胜感激

Thanks

谢谢

采纳答案by Adnan Umer

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

.clone()只克隆 DOM 元素。为了克隆 JavaScript 对象,请尝试jQuery.extend。像这样的东西

// 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.

打字稿转译为 JavaScript。所以,JavaScript 的方式会正常工作。

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>

回答by Bruno Grieder

  • Using standard ES6 features

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

    Warning: this performs a shallow clone.

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

  • A "quick" way of deep cloning is to use JSONutilities

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

  • 使用标准ES6 特性

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

    警告:这将执行浅克隆。

    这个来自 MDN 的优秀页面包含大量关于克隆的细节,包括 ES5 的 polyfill

  • 深度克隆的“快速”方法是使用JSON实用程序

    const clone = JSON.parse(JSON.stringify(myObject))
    
  • 克隆的“正确”方法是实现克隆方法或复制构造函数......

I know, I know, not enough JQuery

我知道,我知道,没有足够的 JQuery

回答by Scot

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

Object.create 创建一个具有空属性的新实例 Object.assign 然后获取该新实例并分配属性

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);
        }
    }

回答by Ondrej Slinták

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

如果您使用的是 TS 2.1,则可以使用对象扩展运算符来创建浅拷贝:

const obj = { a: 1 };
const clonedObj = { ...obj };