前言:我知道这个问题可能在互联网上的某个地方有答案,但我找不到一种方法来表述它以便谷歌给我答案。
上下文: 我正在从事一个涉及在 2D 空间中四处移动的对象的小项目。这些对象中的每一个都有一个位置,该位置包含在 Vector2D 对象中(具有 x 坐标、y 坐标和一些与位置相关的其他逻辑位)。
现在,每当我想对这些对象执行任何类型的数学运算(例如,移动一个对象)时,我都必须通过 X 轴和 Y 轴分离我的计算,这是一个巨大的痛苦。
关于这个问题:是否有某种方法可以在类之间实现运算符(例如“+”或“*”),这样就不必为每个单独的变量编写单独的逻辑?如果是这样,它看起来像什么?
示例: 我想将对象 A 向右移动 4 个单位并向下移动 4 个单位。
现状:
this.ObjectA.x += 4;
This.objectA.y += 4;
理想情况: this.ObjectA += new Vector2D(4,4);
最佳答案
简短回答:不,因为 JavaScript 不支持运算符重载。
TypeScript 问题
到目前为止,TypeScript 没有实现该功能,因为那需要类型相关的发射 (参见 TypeScript/issues/5407)。
One thing we avoid doing is type-driven emit. The idea is that TypeScript types have no bearing at runtime - the code is as close to the analogous JavaScript that you would have written. Given that, substituting in a method call for an operator would go against that.
另一位 TS 维护者表示,他们不会实现未通过 ECMAScript 提案流程的功能(参见 TypeScript/issues/2319)。这背后的原因是为了避免将来可能与官方 ES 语法发生冲突。
ECMA脚本
esdiscuss.org 上有很多关于此功能的讨论。 (有些约会 11 年前......)。在 one of the most recent发表了以下评论:
I recommend to abandon all ideas of operator overloading for arbitrary types - that's extremely unlikely to happen. It's heavily affects optimization possibilities, requires extensive type checks. Moreover, there is no interest from browser vendors to implement it.
因此,操作符重载似乎极不可能出现在 ECMAScript 中。
我该怎么办……
在类上实现一个函数 :) 由于运算符重载只是一个语法糖,您可以通过函数调用实现相同的目的。所以不是这个:
this.ObjectA += new Vector2D(4,4);
这样做:
this.ObjectA.addVector(new Vector2D(4,4));
关于javascript - 在Typescript中实现同一类的两个对象之间的加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46539527/