适用于JavaScript的Python装饰器

用户名

我正在寻找与JavaScript(即@property中的Python装饰器等效的方法,但是我不确定如何做到这一点。

class Example:
    def __init__(self):
        self.count = 0
        self.counts = []
        for i in range(12):
            self.addCount()

    def addCount(self):
        self.counts.append(self.count)
        self.count += 1
    @property
    def evenCountList(self):
        return [x for x in self.counts if x % 2 == 0]


    example = Example()
    example.evenCountList # [0, 2, 4, 6, 8, 10]

我将如何在JavaScript中做到这一点?

哈加兹巴拉

显然,这种确切的语法在Javascript中不存在,但是有一种方法Object.defineProperty可用于实现非常相似的功能。基本上,此方法使您可以为特定对象创建新属性,并作为所有可能性的一部分,定义用于计算值的getter方法。

这是一个简单的示例,可以帮助您入门。

var example = {
    'count': 10
};

Object.defineProperty(example, 'evenCountList', {
    'get': function () {
        var numbers = [];
        for (var number = 0; number < this.count; number++) {
            if(number % 2 === 0) {
                numbers.push(number);
            }
        }
        return numbers;
    }
});

就像@property可以有二传手一样,也可以Object.defineProperty您可以通过阅读MDN上文档来检查所有可能的选项

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章