user3234209 user3234209 - 4 months ago 8
Python Question

Python decorator for JavaScript

I'm looking for the equivalent of a Python decorator in JavaScript (i.e.

@property
) but I'm not sure how to do it.

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 would I do that in JavaScript?

Answer

Obviously this exact syntax doesn't exist in Javascript, but there is a method Object.defineProperty, which 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 possibilities, define the getter method which is used to compute 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;
    }
});

Just as @property can have a setter, so can Object.defineProperty. You can check all the possible options by reading the documentation on MDN.

Comments