Skip to content

Default constructor for subclass now returns returned value from parent #1975

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/nodes.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -896,8 +896,10 @@ exports.Class = class Class extends Base
ensureConstructor: (name) ->
if not @ctor
@ctor = new Code
@ctor.body.push new Literal "#{name}.__super__.constructor.apply(this, arguments)" if @parent
@ctor.body.push new Literal "var instance = this"
@ctor.body.push new Literal "instance = #{name}.__super__.constructor.apply(this, arguments)" if @parent
@ctor.body.push new Literal "#{@externalCtor}.apply(this, arguments)" if @externalCtor
@ctor.body.push new Literal "return instance"
@body.expressions.unshift @ctor
@ctor.ctor = @ctor.name = name
@ctor.klass = null
Expand Down
22 changes: 22 additions & 0 deletions test/classes.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,28 @@ test "constructors with inheritance and super", ->
ok (new SubClass).prop is 'top-super-sub'


test "default constructors for subclasses return value from constructor", ->
class SuperClass
@__identityMap: {}

constructor: (@id) ->
instance = SuperClass.__identityMap[@id]
return instance ?= SuperClass.__identityMap[@id] = this # explicit return required here

class SubClass extends SuperClass

one = new SuperClass(1)

ok (new SuperClass(1) is one)
ok (new SubClass(1) is one)
ok (new SuperClass(2) isnt one)
ok (new SubClass(2) isnt one)

instanceCount = 0
instanceCount += 1 for own key, value of SuperClass.__identityMap
ok (instanceCount is 2)


test "Overriding the static property new doesn't clobber Function::new", ->

class OneClass
Expand Down