开发者

Can I assign Objects operators? "e.g. +, -"

开发者 https://www.devze.com 2022-12-18 03:50 出处:网络
So I have a simple Javascript Object:开发者_运维技巧 function Vector(x, y){ this.x = x; this.y = y;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号