【问题标题】:How can I write constructor within an arithmetic expression?如何在算术表达式中编写构造函数?
【发布时间】:2012-11-18 02:27:27
【问题描述】:

我想减少 JavaScript 中丑陋的代码,尤其是与构造函数相关的代码。

我有一个向量定义为:

function Vector2(X, Y) {
    this.x = 0.0;
    this.y = 0.0;

    if (X)
        this.y = Y;
    if (Y)
        this.y = Y;
}

现在,为了将两个向量相加,我必须这样写:

var vector1 = new Vector2(1.0, 0.5);
var vector2 = new Vector2(4.5, 1.0);

vector1.x += vector2.x;
vector1.y += vector2.y;

我想让代码更漂亮、更易于阅读,并在使用许多构造函数时制作更小的文件。我希望能够写的是:

vector1 += vector2;

提前感谢您的帮助。

【问题讨论】:

    标签: javascript constructor arithmetic-expressions


    【解决方案1】:

    你可以拥有这个:

    function Vector(X, Y) {
        this.x = X || 0.0; // yes, I simplified a bit your constructor
        this.y = Y || 0.0;
    }
    Vector.prototype.add = function(v) {
       this.x += v.x;
       this.y += v.y; 
    }
    

    你只需要这样做

    var vector1 = new Vector(4,4);
    var vector2 = new Vector(1,3);
    vector1.add(vector2);
    

    【讨论】:

    • 这绝对实现了所有目标。我希望有更多类似于重载运算符的方式,类似于您在 C 系列中的方式。无论如何,非常感谢您的快速回答@dystroy。
    【解决方案2】:
    vector1 += vector2;
    

    我不知道你来自什么语言,但你不能覆盖 JavaScript 中的运算符。

    【讨论】:

      猜你喜欢
      • 2014-06-12
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多