Python Decoder for JavaScript

I'm looking for the equivalent of a Python decoder in JavaScript (i.e. @property), but I'm not sure how to do this.

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]

How do I do this in JavaScript?

+4
source share
1 answer

Obviously, this exact syntax does not exist in Javascript, but there is a method Object.definePropertythat can be used to achieve something very similar. Basically, this method allows you to create a new property for a specific object and, as part of all the features, define a getter method that is used to calculate the value.

Here is a simple example to get you started.

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.

+4

Source: https://habr.com/ru/post/1544241/


All Articles