首页 > 解决方案 > Typescript/JSX - 通过引用分配一个类的实例

问题描述

本质上,我希望能够通过引用访问对象的属性。看看下面的代码;

class Point{
  x:number;
  y:number;
  constructor(x,y)
  {
    this.x=x;
    this.y=y;
  }
}

const a = { first: new Point(8,9), second: new Point(10,12) };
let someBool = true;

function modifyProperty(a) {
  let c = someBool? a.first: a.second;

  let newPoint = new Point(0,0);
  c = newPoint;         // Doesn't work

  someBool = !someBool;
}

modifyProperty(a);
console.log(a.first);

在此示例中,每当我调用 modifyProperty() 时,我都想在更改“a”中的两个属性之一之间交替。

但是,当我将 'c' 分配给 'a.first' 或 'a.second' 时,它只会按值传递。我想解决这个问题的唯一方法是使属性本身成为一个对象,如下所示:

 const a = { first: {value: new Point(8,9)}, second: {value: new Point(10,12)} };

然后我会打电话c.value = newPoint来代替。这会起作用,但这不是一个好的解决方案,因为您必须对对象中的每个属性都这样做。

有没有更好的方法来通过引用获取这些属性?我知道 JS 只支持对象和数组的传递引用,但是类的实例呢?

我知道当 Babel 将一个类转换为普通的 Javascript 时,它们被视为函数,但函数不是原始类型——它是一个可调用的对象,所以这不起作用,什么是解决方案?

标签: javascripttypescriptpass-by-referencejsxpass-by-value

解决方案


但是,当我将 'c' 分配给 'a.first' 或 'a.second' 时,它仅按值传递

是的,赋值总是改变左边的东西的值,=没有办法在 Javascript 或 TypeScript 中改变它。

一种解决方法是将属性名称与属性所属的对象一起使用,而不是引用:

type Pair<T> = { first: T, second: T }

function modifyProperty(a: Pair<Point>) {
    let c: keyof Pair<Point> = someBool? 'first' : 'second'; 
    // keyof Pair<Point> type annotation means 
    // that only property names of Pair could be assigned to c  

    let newPoint = new Point(0,0);
    a[c] = newPoint;         

    someBool = !someBool;
}

推荐阅读