是否可以在javascript中添加一些新语法? [英] is it possible to add some new syntax in javascript?

查看:85
本文介绍了是否可以在javascript中添加一些新语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在javascript中添加一些新语法?就像我希望它有一个类似的synatx:

Is it possible to add some new syntax into javascript? Like if I want it to have a synatx like:

mul> 10> 20 并且结果 200 或者如果说 mul(2)(3),结果为6?有可能的?我在某个地方看到了类似的问题吗?所以我不确定它是否可能?如果不是在JS中,它可以在其他语言中使用,如C,Java,Python吗?我的理解是,所有这些语言只能为新对象添加一些功能,甚至那些新对象只能拥有语言本身已有的运算符和语法?我是正确的还是可以为这些语言添加新语法?

mul>10>20 and it result 200 or if say mul(2)(3) and it result as 6 ? It is possible? I saw similar question somewhere to do this? So I am not sure if it is possible or not? If not in JS is it possible in other languages like C, Java, Python ? My understanding is that all these languages are only able to add some functionality for new objects and even those new objects can only have operators and syntax that a language itself already have? So am I correct or this is possible to add new syntax to these langauges?

推荐答案

在Python中

mul(2)(3)

表示使用参数 2 调用 mul ,然后调用 return 来自参数 3 的值(假设它是一个函数)。您无法重新定义该语法,但您可以使用它来运行:

means call mul with argument 2, then call the return value from that with argument 3 (which assumes that it's a function). You can't redefine that syntax, but you could make your function work with it:

def mul(arg):
    return lambda x: x * arg

允许链接(即 mul (2)(3)(4))我会去

To allow chaining (i.e. mul (2)(3)(4)) I would go for a class:

import operator

class op(object):

    def __init__(self, op, arg):
        self.op = op
        self.value = self._get_val(arg)

    def _get_val(self, arg):
        try:
            return arg.value
        except AttributeError:
            return arg

    def __repr__(self):
        return str(self.value)

    def __call__(self, arg):
        self.value = self.op(self.value, 
                             self._get_val(arg))
        return self

    def __getitem__(self, key):
        self.value = self.op(self.value, 
                             -1 * self._get_val(key))
        return self


class mul(op):

    def __init__(self, arg):
        super(mul, self).__init__(operator.mul, arg)

我添加了奖励功能,方括号使参数为负( mul(2)[3] == -6 )。这只假装返回一个数字;我将其余必要的魔术方法作为练习给读者留下。

I have added a bonus feature, square brackets make the argument negative (mul(2)[3] == -6). This only pretends to return a number; I leave implementing the rest of the necessary magic methods as an exercise for the reader.

你不能让 mul> x> y 做除返回 x以外的任何事情> y True False ),作为函数对象 mul 将评估为大于任何整数。

You couldn't make mul>x>y do anything other than return x > y (True or False), as the function object mul will evaluate as larger than any integers.

这篇关于是否可以在javascript中添加一些新语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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