gpt4 book ai didi

javascript - 我可以分配对象运算符吗? "e.g. +, -"

转载 作者:行者123 更新时间:2023-11-30 13:41:23 24 4
gpt4 key购买 nike

所以我有一个简单的 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 实现就太好了


非常感谢您的帮助。谢谢! :)

最佳答案

这在 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);

关于javascript - 我可以分配对象运算符吗? "e.g. +, -",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2127925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com