Can I assign Objects operators? "e.g. +, -"
So I have a simple Javascript Object:开发者_运维技巧
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){}
//...
}
I would like to perform the following operations:
var a = new Vector(1,1);
var b = new Vector(10,5);
var c = a + b
a += c;
// ... and so on
I know that it's possible to implement operators for Objects in other languages, would be great if I could do it in Javascript
Help would be very much appreciated. Thanks! :)
This isn't possible in JavaScript.
You can specify what happens to your object in numerical contexts:
Vector.prototype.valueOf = function() { return 123; };
(new Vector(1,1)) + 1; // 124
... but I don't think this is what you're after.
How about offering a plus
method? -
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);
Sorry, ECMAScript/Javascript doesn't support operator overloading. It was proposed for ECMAScript 4 but the proposal wasn't accepted. You can still define a method which does the same thing as +
, though -- just call .add()
instead.
精彩评论