简体   繁体   中英

How to access class parameter from class property in coffeescript?

I have such base class:

class Base
  loginForm: {}

  constructor: (@data) ->
    @username = @data.username
    @password = @data.password

  log: ->
    console.log @loginForm

and the child class, which should look like this:

class Child extends Base
  loginForm: 
    accountname: @username.split('/')[0]
    username: @username.split('/')[1]
    password: @password

child = new Child username: 1, password: 2

Obviously, if we do child.log() we'll see

Child.username is undefined

So, the question is how can I use properties, that are set inside constructor in other properties definition (or class parameter inside class property)?

The code above is simplified version of what I have, but it completely shows what I need to achieve (please, do not suggest me to create separate properties for each of @username.split('/') in base class constructor).

Here is corresponding jsFiddle

I know I can do something like

class Base
  loginForm: {}

  constructor: (@data) ->
    @username = @data.username
    @password = @data.password
    @init()

  init: ->

class Child extends Base
  init: ->
    @loginForm =
      accountname: @username.split('/')[0]
      username: @username.split('/')[1]
      password: @password

but I would love not to (I don't like how it looks).

You have to call the parent constructor by using super :

class Base
  loginForm: {}

  constructor: (@data) ->
    @username = @data.username
    @password = @data.password

  log: ->
    console.log @loginForm

class Child extends Base
  constructor: (@data) ->
    super(@data)
  init: ->
    @loginForm =
      accountname: @username.split('/')[0]
      username: @username.split('/')[1]
      password: @password

And when you create an instance of Child , pass the data so that the parent Base get's it in it's constructor.

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