简体   繁体   中英

Python decorator for JavaScript

I'm looking for the equivalent of a Python decorator in JavaScript (ie @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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM