是否可以在JavaScript中创建自定义运算符? [英] Is it possible to create custom operators in JavaScript?

查看:111
本文介绍了是否可以在JavaScript中创建自定义运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Math课程中,我们学习了如何定义新的运算符。例如:

During the Math classes we learned how to define new operators. For example:

这定义了法律。对于任何实数 x y x∘y x + 2y

This defines law. For any real numbers x and y, x ∘ y is x + 2y.

示例:2∘2= 2 + 4 = 6

可以在JavaScript中定义这样的运算符吗?我知道函数可以完成这项任务:

Is possible to define operators like this in JavaScript? I know that a function would do the job:

function foo (x, y) { return x + 2 * y; }

但我希望使用以下语法:

but I would like to have the following syntax:

var y = 2 ∘ 2; // returns 6

而不是:

var y = foo(2, 2);

这个问题最接近的解决方案是什么?

Which is the closest solution to this question?

推荐答案

简短的回答是否定的。 ECMAScript(标准JS基于)不支持运算符重载。

The short answer is no. ECMAScript (the standard JS is based on) does not support operator overloading.

另外,在ECMAScript 7中,您将能够重载子集设计自定义值类型时的标准运算符。这是一个关于这个主题的由语言创建者和Mozilla CTO Brendan Eich组成的幻灯片。但是,这不允许任意操作符,并且重载的含义只会应用于值类型。< - 哈哈最终没有发生。

As an aside, in ECMAScript 7, you'll be able to overload a subset of the standard operators when designing custom value types. Here is a slide deck by language creator and Mozilla CTO Brendan Eich about the subject. This won't allow arbitary operators, however, and the overloaded meaning will only be applied to value types. <- haha that ended up not happening.

可以使用 sweet.js 等第三方工具添加自定义运算符,但这需要额外的编译一步。

It is possible to use third party tools like sweet.js to add custom operators though that'd require an extra compilation step.

使用esprima回答了来自外部JavaScript的解决方案 - 这是更改 JavaScript并扩展它,它不是原生的。

I've answered with a solution from outside JavaScript using esprima - this is changing JavaScript and extending it, it's not native.

这篇关于是否可以在JavaScript中创建自定义运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆