Extending Classes with new properties without overriding the main constructor

StackOverflow https://stackoverflow.com/questions/23346691

  •  11-07-2023
  •  | 
  •  

سؤال

Considering the usual Personclass:

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 Personconstructor, 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.

هل كانت مفيدة؟

المحلول

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

Working example here

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top