2010-01-24 71 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()即可。

相關問題