Support ES6 method-shorthand constructors in extend (#4213)#4300
Open
BigBalli wants to merge 1 commit intojashkenas:masterfrom
Open
Support ES6 method-shorthand constructors in extend (#4213)#4300BigBalli wants to merge 1 commit intojashkenas:masterfrom
BigBalli wants to merge 1 commit intojashkenas:masterfrom
Conversation
ES6 method shorthand (`constructor() {}`) produces a non-constructable
function with no `prototype` property. Passing such a constructor to
`extend` previously caused `new Subclass()` to throw
"Subclass is not a constructor".
Detect the shorthand case (absence of `prototype`) and wrap the
supplied constructor in a thin function so `new` continues to work.
The traditional `constructor: function() {}` form is unchanged.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4213.
Problem
ES6 method shorthand (
constructor() {}) produces a non-constructablefunction with no
prototypeproperty. Passing such a constructor toextendpreviously causednew Subclass()to throwSubclass is not a constructor:This forces users on modern JS to write the awkward mixed form
(
constructor: function() {}next to method shorthand) or to give up onextendaltogether.Fix
Detect the shorthand case by checking for the absence of
prototypeonthe supplied constructor, and in that case wrap it in a thin function so
newcontinues to work. The traditionalconstructor: function() {}form is unchanged and still uses the supplied function directly, so the
edge case noted in the issue (
Model === proto.constructor) remainstrue for ES5 users.
Test
Added a regression test in
test/model.jsthat defines theconstructorvia ES6 method shorthand (constructed viaevalso thetest file still parses on engines without shorthand support) and
verifies that
new Model({foo: 'bar'})returns a usable instance.npm run lintpasses.