javascript - 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 时,它们被视为函数,但函数不是原始类型——它是一个可调用的对象,所以这不起作用,什么是解决方案?
解决方案
但是,当我将 '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;
}
推荐阅读
- c# - 有没有办法从 json 声明和设置类的变量?
- opencv - 找到暗网 OpenCV 但无法演示
- excel - Excel VBA 宏给出了意想不到的结果?
- akka - 如何在测试中禁用 Akka 死信警告
- python - 如何在 python 终端中的 ax,y 位置上书写(基于文本)
- node.js - 我在一个应用程序中有两个版本的 React Native
- python - Django - MySQL 中超过一百万条记录的 Q 查找搜索速度很慢
- javascript - javascript 条件语法运行不正常
- python - Python Pandas中DataFrame中的天数计算?
- sql - Oracle SQL 通过从另一条记录中获取随机数据来更新一条记录中的字段(个人信息字段)