[英]Can I assign Objects operators? “e.g. +, -”
So I have a simple Javascript Object: 所以我有一个简单的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){}
//...
}
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 我知道可以用其他语言实现对象的运算符 ,如果我可以用Javascript来实现,那将是很好的
Help would be very much appreciated. 帮助将不胜感激。 Thanks!
谢谢! :)
:)
This isn't possible in JavaScript. 这在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? 如何提供
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);
Sorry, ECMAScript/Javascript doesn't support operator overloading. 抱歉,ECMAScript / Javascript不支持运算符重载。 It was proposed for ECMAScript 4 but the proposal wasn't accepted.
它是为ECMAScript 4提出的,但是没有被接受。 You can still define a method which does the same thing as
+
, though -- just call .add()
instead. 不过,您仍然可以定义一个与
+
具有相同功能的方法-只需调用.add()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.