2010-01-24 67 views
1

所以我有一个简单的的Javascript对象:我可以分配对象操作符吗? “例如+, - ”

function Vector(x, y){ 
    this.x = x; 
    this.y = y; 

    this.magnitude = function(){}; 
    this.add = function(vector){}; 
    this.minus = function(vector){}; 
    this.normalise = function(){}; 
    this.dot = function(vector){} 

    //... 
} 

我想执行以下操作:

var a = new Vector(1,1); 
var b = new Vector(10,5); 
var c = a + b 
a += c; 
// ... and so on 

我知道这是可能的为其他语言的对象实施运营商,如果我可以在Javascript中执行,将会非常好用


帮助将非常感激。谢谢! :)

+0

您正在寻找的术语是“过载”。 – 2010-01-24 17:13:11

+1

我会建议你让Vector在执行该操作之前返回一些值并删除'new',所以它就像var a = Vector(1,1); – Reigel 2010-01-24 17:15:52

+0

谢谢Reigel!你能向我展示你的意思吗? :) – RadiantHex 2010-01-24 17:17:05

回答

3

这在JavaScript中不可行。

您可以指定会发生什么你的对象在数字环境中:

Vector.prototype.valueOf = function() { return 123; }; 

(new Vector(1,1)) + 1; // 124 

...但我不认为这是你追求的。

如何提供plus方法? -

Vector.prototype.plus = function(v) { 
    return /* New vector, adding this + v */; 
}; 

var a = new Vector(1,1); 
var b = new Vector(10,5); 
var c = a.plus(b); 
+0

谢谢,这是有帮助的。我已经有了加法,但我真的很讨厌它。 :) – RadiantHex 2010-01-24 17:19:37

0

对不起,ECMAScript/Javascript不支持运算符重载。它被提议用于ECMAScript 4,但该提案未被接受。您仍然可以定义一个与+完全相同的方法 - 只需调用.add()即可。

相关问题