我可以在 Javascript 中定义自定义运算符重载吗? [英] Can I define custom operator overloads in Javascript?
本文介绍了我可以在 Javascript 中定义自定义运算符重载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在 JavaScript 中的类型实例之间定义自定义运算符?
Is it possible to define custom operators between instances of a type in JavaScript?
例如,假设我有一个自定义向量类,是否可以使用
For example, given that I have a custom vector class, is it possible to use
vect1 == vect2
检查相等性,而底层代码是这样的?
to check for equality, whilst the underlying code would be something like this?
operator ==(a, b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
(当然这是废话.)
推荐答案
我同意向量原型上的相等函数是最好的解决方案.请注意,您还可以通过链接构建其他类似中缀的运算符.
I agree that the equal function on the vector prototype is the best solution. Note that you can also build other infix-like operators via chaining.
function Vector(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Vector.prototype.add = function (v2) {
var v = new Vector(this.x + v2.x,
this.y + v2.y,
this.z + v2.z);
return v;
}
Vector.prototype.equal = function (v2) {
return this.x == v2.x && this.y == v2.y && this.z == v2.z;
}
您可以在此处查看在线示例.
更新:这是创建工厂函数的更广泛示例支持链接.
Update: Here's a more extensive sample of creating a Factory function that supports chaining.
这篇关于我可以在 Javascript 中定义自定义运算符重载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文