克隆TypeScript对象 [英] Cloning a TypeScript Object

查看:88
本文介绍了克隆TypeScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个打字稿类

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

}

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

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

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

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.

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

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

我尝试过使用jQuery.clone并进行扩展,但它似乎不起作用,我认为这是因为它是一个打字稿对象。或者那不重要吗?

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?

任何关于如何克隆这个对象的答案都将不胜感激

Any answers on how to clone this object would be appreciated

谢谢

推荐答案

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

.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转换为JavaScript。因此,JavaScript方式可以正常工作。

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

演示:

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

这篇关于克隆TypeScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆