如您所见,Javascript不支持运算符重载。您可以执行的最接近的是实现
toString(当实例需要被强制为字符串时
valueOf将被调用)和(被强制将其强制为一个数字,例如在
+用于加法时,或者在许多情况下,使用它进行串联,因为它
+尝试在串联之前进行加法),这非常有限。两者都不会让您创建
Vector2对象。
不过,对于遇到此问题的人想要一个字符串或数字(而不是
Vector2),下面是
valueOf和的示例
toString。这些示例 没有
演示运算符重载,只是利用了Javascript的内置处理将其转换为原语:
valueOf
此示例将对象
val属性的值加倍以响应被强制转换为原语,例如通过
+:
function Thing(val) { this.val = val;}Thing.prototype.valueOf = function() { // Here I'm just doubling it; you'd actually do your longAdd thing return this.val * 2;};var a = new Thing(1);var b = new Thing(2);console.log(a + b); // 6 (1 * 2 + 2 * 2)或搭配ES2015
class:
class Thing { constructor(val) { this.val = val; } valueOf() { return this.val * 2; }}const a = new Thing(1);const b = new Thing(2);console.log(a + b); // 6 (1 * 2 + 2 * 2)或仅包含对象,没有构造函数:
var thingPrototype = { valueOf: function() { return this.val * 2; }};var a = Object.create(thingPrototype);a.val = 1;var b = Object.create(thingPrototype);b.val = 2;console.log(a + b); // 6 (1 * 2 + 2 * 2)toString
本示例将对象
val属性的值转换为大写形式,以响应被强制转换为原语,例如通过
+:
function Thing(val) { this.val = val;}Thing.prototype.toString = function() { return this.val.toUpperCase();};var a = new Thing("a");var b = new Thing("b");console.log(a + b); // AB或搭配ES2015
class:
class Thing { constructor(val) { this.val = val; } toString() { return this.val.toUpperCase(); }}const a = new Thing("a");const b = new Thing("b");console.log(a + b); // AB或仅包含对象,没有构造函数:
var thingPrototype = { toString: function() { return this.val.toUpperCase(); }};var a = Object.create(thingPrototype);a.val = "a";var b = Object.create(thingPrototype);b.val = "b";console.log(a + b); // AB


