javascript - ES6 Class 使得构造函数 "+"能够被使用

标签 javascript class ecmascript-6

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 方法。

最佳答案

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

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

你可以这样尝试:

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

关于javascript - ES6 Class 使得构造函数 "+"能够被使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58200556/

相关文章:

javascript - ES6 : access to inherited class'es properties and methods from the parent class

javascript - 在 Symfony 4 中通过 ES6 使用 jQuery

Javascript 对象 [排序]

javascript - 正则表达式 if else 语句失败

c++ - 从不同的 C++ 类访问 Mysql * 连接变量

c++ - gdb 打印命令中自静态包含字符串子类的递归输出

c++ - 未声明的标识符 xcode c++

javascript基于另一个更大的数组创建具有固定长度的对象数组

javascript - 如何使用 eslint 修复一条规则

javascript - Twitter Bootstrap 弹出窗口 : repositioning or resizing after dynamically generating data?