【问题标题】:Typescript/JSX - Assign an instance of a class by referenceTypescript/JSX - 通过引用分配一个类的实例
【发布时间】:2019-04-29 16:22:28
【问题描述】:

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

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 时,它们被视为函数,但函数不是原始类型 - 它是一个可调用的对象,所以这不起作用,什么是解决方案?

【问题讨论】:

    标签: javascript typescript pass-by-reference jsx pass-by-value


    【解决方案1】:

    但是,当我将 '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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-13
      • 2022-12-21
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多