2014-06-11 76 views
4

我正在尋找相當於JavaScript的Python裝飾器(即@property),但我不知道該怎麼做。JavaScript的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呢?

回答

4

顯然這個確切的語法在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。您可以通過閱讀documentation on MDN來檢查所有可能的選項。

+0

還有get和set語法可以在聲明對象字面值時進行內聯,如果您希望它更接近內聯的@property:https://developer.mozilla.org/en-US/docs/Web/的JavaScript /參考/運營/獲取 – slebetman