【问题标题】:How to access child model static from parent within Coffeescript inhertiance如何在 Coffeescript 继承中从父级访问子模型静态
【发布时间】:2013-05-13 23:41:23
【问题描述】:

我有以下BaseModel

namespace 'Models', (exports) ->
  class exports.BaseModel
    toJSON: =>
      if @jsonProperties? then ko.toJSON( @, @jsonProperties() ) else null

然后我的Profile类继承了BaseModel

namespace 'Models', (exports) ->
  class exports.Profile extends exports.BaseModel
    constructor: ( @options ) ->
      @FirstName = ko.observable( @options.FirstName )
      @LastName = ko.observable( @options.LastName )

  @jsonProperties: -> 
    return [ "FirstName", "LastName" ]

这让我可以调用类似下面的东西

profile = new Models.Profile
  FirstName: 'blah'
  LastName: 'blah'   

profile.toJSON()

但是在基本模型中@jsonPropertiesundefined,因为它有点像类类型上的静态函数。我想要这个的原因是我可以在其他类中引用它,比如Models.Profile.jsonProperties()

我是否可以从 BaseModel 中访问类似的内容?


编辑:添加一个占位符修复,直到我想出更好的东西

我已完成以下操作以使其正常工作,但我宁愿不必在我创建的每个模型中重复这一行,似乎应该有一个通用的方法可以从 BaseModel 执行此操作。

namespace 'Models', (exports) ->
  class exports.Profile extends exports.BaseModel
    constructor: ( @options ) ->
      @jsonProperties = Models.Profile.jsonProperties

【问题讨论】:

  • 我想出了一个方法,但它有点危险 - 在 BaseModel 中有函数 @json return Models[@.constructor.name].jsonProperties() 访问父级。但是,这不适用于 IE。不过可能有一种解决方法。
  • Function.name 不是标准的 AFAIK
  • 是的 :( 很糟糕,javascript 中没有任何东西可以让你做到这一点。对元编程真的很有帮助

标签: javascript coffeescript


【解决方案1】:

如果我理解您想要实现的目标,您可以通过将 jsonProperties 定义为“静态”类方法和实例方法来修复它。这是一个简化的代码(无权访问namespace util 和敲除):

class BaseModel
  toJSON: =>
    if @jsonProperties? 
      for value in @jsonProperties()
        @[value]
    else
      null

class Profile extends BaseModel
  constructor: ( @options ) ->
    @FirstName = @options.FirstName
    @LastName = @options.LastName

  @jsonProperties: -> 
    return [ "Class FirstName", "Class LastName" ]

  jsonProperties: -> 
    return [ "FirstName", "LastName" ]

prof = new Profile
  FirstName: 'Leandro'
  LastName: 'Tallmaris'   

alert(prof.toJSON());

alert(Profile.jsonProperties());

第一个警报应该给你Leandro, Tallmaris,而第二个警报应该给你Class FirstName, Class SecondName

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2021-05-07
    相关资源
    最近更新 更多