How would you extend a class using CoffeeScript, but have the construction arguments passed to super?
Eg:
class List extends Array
# Some other stuff to make it work...
list = new List(1,2,3)
console.log list
[1, 2, 3]
If we include “this()” or “super()” inside the constructor, it must be the first statement inside it. “this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement). “this” can be passed as an argument in the method and constructor calls.
In AS2, you can pass parameters to a super class's constructor using super() . This is handy, but what if your constructor accepts an undefined number of parameters, and you want to pass them all to your super constructor (think of the Array class, for instance)? Sounds easy – you should just be able to use “super.
Using super in classes Here super() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square .
Use of super() to access superclass constructor As we know, when an object of a class is created, its default constructor is automatically called. To explicitly call the superclass constructor from the subclass constructor, we use super() .
In general, this would work without additional code; the parent constructor is used unless expressly overridden:
class A
constructor: ->
console.log arg for arg in arguments
class B extends A
new B('foo') # output: 'foo'
And the problem isn't that Array doesn't have a constructor
method:
coffee> Array.constructor
[Function: Function]
The problem is just that Array
is just plain weird. While arrays are "just objects" in principle, in practice they're stored differently. So when you try to apply that constructor to an object that isn't an array (even if it passes the instanceof Array
test), it doesn't work.
So, you can use Acorn's solution, but then you may run into other problems down the road (especially if you pass a List
to something that expects a true array). For that reason, I'd recommend implementing List
as a wrapper around an array instance, rather than trying to use inheritance from a native object type.
While we're on the subject, one very important clarification: When you use super
by itself, that does pass all arguments! This behavior is borrowed from Ruby. So
class B extends A
constructor: ->
super
will pass along all arguments to A
's constructor, while
class B extends A
constructor: ->
super()
will invoke A
's constructor with no arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With