【问题标题】:ES6 Class make constructor "+" be able to be used [duplicate]ES6类使构造函数“+”能够被使用[重复]
【发布时间】:2020-01-31 16:14:03
【问题描述】:
class Vector {
    constructor(x,y) {
      this.x = x || 0;
      this.y = y || 0;
    }

    add = function (c) {


        return new Vector(this.x + c.x,this.y+c.y)
    };


  }

我希望能够做到 new Vector(4,4) + new Vector(0,2) --> Vector(4,6)。 我尝试更改多个部分并查看,但我发现最接近的是旧的 ES5 方法。

【问题讨论】:

  • 您不能重载+ 运算符。最多,您可以更改使用+ 时实例转换为的原语,但这会在操作后为您提供原语。您可以创建一个方法来处理操作(就像您在此处所做的那样)。
  • 不相关,但在这里使用add = function(otherarray) { 而不是add(otherarray) { 会更长且更少性能且收益为零。

标签: javascript class ecmascript-6


【解决方案1】:

其他答案已经指出,你不能在javascript中重载运算符,所以我们可以做的是查看你正在使用的add方法。

看起来它不起作用,因为您没有将第二个 Vector 中的值添加到结果中。

你可以这样试试:

add = function (otherVector) {
    return new Vector(this.x + otherVector.x, this.y + otherVector.y)
};

【讨论】:

    猜你喜欢
    • 2015-12-01
    • 2018-05-11
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多