user3234209 user3234209 - 1 year ago 96
Python Question

Python decorator for JavaScript

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

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

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

def addCount(self):
self.count += 1
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 Source

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) {
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download