Reputation: 1481
Considering the usual Person
class:
class Person
constructor: (@firstName, @lastName) ->
sayName: ->
console.log "Hi, im #{@firstName} #{@lastName}"
I then want to extend this class with a new one, called Employee
that has an additional property position
:
class Employee extends Person
constructor: (@position) ->
The problem with this is that im overriding the Person
constructor, so my employees instances won't get the firstName
and lastName
variables.
What would be the best way to achieve this, without redefining the constructor function and inheriting those properties from the Person
class?
Thanks.
Upvotes: 0
Views: 48
Reputation: 187004
Uh, well, you've overridden the ability to accept a first and last name in the constructor. So I'm guessing you want to accept the base classes constructor arguments as well as additional arguments?
Something like this could work with any number of arguments from the base class constructor.
class Person
constructor: (@firstName, @lastName) ->
sayName: ->
console.log "Hi, im #{@firstName} #{@lastName}"
class Employee extends Person
constructor: (args..., @position) -> super
dude = new Employee 'Shooty', 'McFace', 1
dude.sayName() # Hi, im Shooty McFace
console.log "position: #{ dude.position }" # position: 1
Here we use a splat (the ...
) to soak up any arguments that we don't need to name. All these arguments get implicitly passed to super
which is the base class constructor. The last argument will be the additional argument you want to capture.
Upvotes: 1