Skip to content

Allow extending native classes - #7081

Closed
nicolo-ribaudo wants to merge 6 commits into
babel:masterfrom
nicolo-ribaudo:extend-native-class
Closed

nicolo-ribaudo wants to merge 6 commits into
babel:masterfrom
nicolo-ribaudo:extend-native-class

Conversation

@nicolo-ribaudo

@nicolo-ribaudo nicolo-ribaudo commented Dec 20, 2017 •

Copy link
Copy Markdown
Member
Q                       A
Fixed Issues? #7022
Patch: Bug Fix?
Major: Breaking Change?
Minor: New Feature? yes
Tests Added + Pass? Yes
Documentation PR
Any Dependency Changes?
License MIT

Allow extending native classes

Use Reflect.construct(Super, ...) instead of Super.apply
when possible, because native classes can't be .applyed.

If a browser doesn't support Reflect.construct, it also doesn't
support class {}.

This is needed when an external modules ships untranspiled classes but the consumer code transpiles them. (This should't happen with preset-env correctly configured, but if you use preset-es2015 your classes might be transpiled even if not needed)

Ref #7078 #7020 (comment)

cc @Kovensky

Use `Reflect.construct(Super, ...)` instead of `Super.apply`
when possible, because native classes can't be `.apply`ed.

If a browser doesn't support `Reflect.construct`, it also doesn't
support `class {}`.
@babel-bot

babel-bot commented Dec 20, 2017 •

Copy link
Copy Markdown
Collaborator

Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/6309/

@nicolo-ribaudo nicolo-ribaudo added the PR: New Feature 🚀 A type of pull request used for our changelog categories label Dec 20, 2017
export default function _constructSuperInstance(Derived, args, existingThis) {
const Super = Derived.__proto__ || Object.getPrototypeOf(Derived);
return typeof Reflect !== "undefined" && typeof Reflect.construct === "function"
? Reflect.construct(Super, args, existingThis.constructor || Derived)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also said this in the comment where I suggested this to begin with, but this has the same caveat as the new.target transform: the this.constructor property must not be tampered with, as it's the only hint we have as to what the instance's constructor is in ES5. All other methods available that appear to work at first glance would break if the class is subclassed.


babelHelpers.classCallCheck(this, Foo);
return babelHelpers.possibleConstructorReturn(_this, (_temp = _this = babelHelpers.possibleConstructorReturn(this, (Foo.__proto__ || Object.getPrototypeOf(Foo)).call(this, ...args)), Object.defineProperty(babelHelpers.assertThisInitialized(_this), "bar", {
return babelHelpers.possibleConstructorReturn(_this, (_temp = _this = babelHelpers.possibleConstructorReturn(this, babelHelpers.constructSuperInstance(Foo, [...args], this)), Object.defineProperty(babelHelpers.assertThisInitialized(_this), "bar", {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible future microoptimization: [...args] -> args

Only possible if we can prove args is arraylike, though 🤷‍♀️

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there something that prevents doing it now? We could use Array.isArray and its helper.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xtuc the idea is to do the optimization statically, though. It'd also miss out on arraylike that are not arrays

// Ensure that we don't try to call super() in the default constructor.
class D extends null {}
var d = new D();
assert.throws(() => new D());

@Jessidhia Jessidhia Dec 21, 2017 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder what happened with TC39's proposal to actually make extends null work.

As it is specified right now (and implemented by engines), extends null is explicitly allowed as a special case, but it's impossible to actually construct such a class.

helpers.constructSuperInstance = defineHelper(`
export default function _constructSuperInstance(Derived, args, existingThis) {
const Super = Derived.__proto__ || Object.getPrototypeOf(Derived);
return typeof Reflect !== "undefined" && typeof Reflect.construct === "function"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While checking if my assumptions were really correct, I found that, while Node 4 has an (incomplete and almost unusable) implementation of classes, it also does not have Reflect, at all.

However, all that changes with this helper is that nothing changes on Node 4, you still can't extend native classes 😄

I also checked whether spreading arguments was safe; while Node 4 has no support for spread at all, arguments does have a working Symbol.iterator, so we should be safe on that side as well if the user uses transform-spread.

@Jessidhia Jessidhia left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀👌

Just want to add something about this on the README: #7081 (comment)

- Babel transpiles classes using `SuperClass.apply(/* ... */)`, but native
classes aren't callable and thus throw in this case.
- When extending native classes the `this.constructor` must not be tampered,
since it is the only way that Babel has of obtaining the class constructor.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This affects all classes, not just the native ones 🤔

- Babel transpiles classes using `SuperClass.apply(/* ... */)`, but native
classes aren't callable and thus throw in this case.
- When extending native classes the `this.constructor` must not be tampered,
since it is the only way that Babel has of obtaining the class constructor.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This affects all classes, not just the native ones 🤔

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh dang, would it be a regression?

@Jessidhia Jessidhia Jan 9, 2018 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A tradeoff. The ability to mess with this.constructor for the ability to extend native classes.

I think it's fine to do it as a breaking change in babel 7.

Erasing this.constructor will break subclassing, unless it's defined to undefined or erased in all prototype levels, because of the || Derived in the helper:

class A {}
class B extends A {}
delete B.prototype.constructor
;(new B()) instanceof B // false; is an `A`
class C extends B {}
C.prototype.constructor = undefined
;(new C()) instanceof C // true

Defining constructor to be something else usually summons Cthulhu.


babelHelpers.classCallCheck(this, Foo);
return babelHelpers.possibleConstructorReturn(_this, (_temp = _this = babelHelpers.possibleConstructorReturn(this, (Foo.__proto__ || Object.getPrototypeOf(Foo)).call(this, ...args)), Object.defineProperty(babelHelpers.assertThisInitialized(_this), "bar", {
return babelHelpers.possibleConstructorReturn(_this, (_temp = _this = babelHelpers.possibleConstructorReturn(this, babelHelpers.constructSuperInstance(Foo, [...args], this)), Object.defineProperty(babelHelpers.assertThisInitialized(_this), "bar", {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there something that prevents doing it now? We could use Array.isArray and its helper.

@loganfsmyth

Copy link
Copy Markdown
Member

Is this something we're still pursuing?

@nicolo-ribaudo

Copy link
Copy Markdown
Member Author

Yes: this PR allows libraries which are distributed with transpiled classes to be used alongise with untranspiled classes.
We could ask users to always transpile their classes in these cases, but I don't think that it would be the correct approach.

@nicolo-ribaudo

Copy link
Copy Markdown
Member Author

I will open another PR; this is too hard to rebase

@nicolo-ribaudo
nicolo-ribaudo deleted the extend-native-class branch September 8, 2018 12:21
@lock lock Bot added the outdated A closed issue/PR that is archived due to age. Recommended to make a new issue label Oct 4, 2019
@lock lock Bot locked as resolved and limited conversation to collaborators Oct 4, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

outdated A closed issue/PR that is archived due to age. Recommended to make a new issue PR: New Feature 🚀 A type of pull request used for our changelog categories

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants