栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Javascript:运算符重载

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Javascript:运算符重载

如您所见,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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464640.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号