簡體   English   中英

兒童班的Coffeescript extern物業商店

[英]Coffeescript extern property store for child class

我使用熱重載類在nodejs(最新版本)中編寫程序。

這意味着我創建了一些對象,在程序中使用它們並更改了它們的屬性和變量。 然后,我更改一些類的源代碼,再次要求其文件並重新創建每個對象。

將新對象鏈接到以前的狀態后,所有以前的屬性和變量都應該像以前一樣可用。

並且對它們的每個訪問操作都應轉移到隱式存儲。 (store = this),但父類方法也應該可用。

我猜想在連接到存儲后重新聲明所有不純函數(依賴存儲)是必要的操作。

如何更改父類以獲取此行為?

說明:

Class B class A擴展了具有屬性和方法的class A

我也有B類的對象store對象b在構造函數中獲取。

所有的方法和屬性,我的孩子申報應包含store

我可以執行以下操作嗎?如何執行?

碼:

store = {}
class A
    constructor: (store)->
        @val = 10
        # some actions with 'store' there or anywhere
        # but child class

class B extends A
    constructor: ->
        super
        @val2 = 20

b = new B(store)
console.log b.val           
console.log b.val2          
console.log store.val2

# I GET -> I WANT TO GET
# 10 -> 10
# 20 -> undefined
# undefined -> 20

jsfiddle工作示例

工作意味着沒有語法錯誤

編輯(26.02.16):

對不起,例子不好

編輯(26.02.16):

擴展了說明。

您必須編寫子類構造函數,以便將其屬性顯式地放置在該存儲上,而不是實例上:

store = {}
class A
    constructor: ->
        @val = 10

class B extends A
    constructor: (s) ->
        super
        s.val2 = 20

b = new B(store)
console.log b.val # 10           
console.log b.val2 # undefined      
console.log store.val2 # 20

真的沒有辦法解決這個問題。

您可以嘗試使用Proxy 在B構造函數中創建它,然后從B構造函數返回它。 代理將以這樣的方式設置:它將所有屬性寫入和讀取轉發給store但B原型中存在的那些(從A繼承的)除外,這些屬性應被轉發到B的真實實例或直接轉發到B的原型。

不知道是否可以在nodejs上運行它,因為Proxy是ES6功能,尚未在節點上本地支持。 巴別塔也不支持它。 它在Firefox,MS Edge和即將推出的Chrome版本中可用。

https://kangax.github.io/compat-table/es6/#test-Proxy

有一個使用MS javascript引擎而不是Chrome的V8的nodejs版本,但我沒有使用過它,也不知道它是否具有代理對象: https : //github.com/nodejs/node-chakracore

我發現,如果知道類更改的時間,則可以用非常簡單的方法解決特定問題。

如何完成熱類重載 (算法):

  1. (班次變更A1A2時刻)
  2. 將對象a自身屬性保存到外部對象store
  3. 用類A2重新創建對象a
  4. 從對象store加載屬性

碼:

store = {}
class A
  constructor: -> @val = 10

  saveTo: (store)->
    for own name, val of @
      store[name] = val

  loadFrom: (store)->
    for own name, val of store
      @[name] = val

class B1 extends A
  dataChange: -> @val2 = 20
class B2 extends A

b = new B1 ; b.dataChange()
console.log b # GOT : B1 {val: 10, val2: 20}
# RELOADED class
store = {}
b.saveTo(store)
# RECREATION of new object
b = new B2
b.loadFrom(store)
console.log b # GOT : B2 {val: 10, val2: 20}

jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM