Skip to content

transform-class-properties: Static arrow functions are bound to undefined rather than the class #5222

@natevw

Description

@natevw

When using babel-plugin-transform-class-properties, it turns out that extending the https://babeljs.io/docs/plugins/transform-class-properties/ example to include a "boundStaticFunction" fails:

  class Bork {
    static staticProperty = "babeliscool";
    static staticFunction = function() {
      return Bork.staticProperty;
    }
    static boundStaticFunction = () => {
      return this.staticProperty
    }
  }

  //Static function exists on the class.
  console.log(Bork.staticFunction()); // > "babelIsCool"
  
  // BUG: static functions cannot be bound to class!
  let fn = Bork.boundStaticFunction
  console.log(fn())

Expected behavior

Calling (Bork.boundStaticFunction)() should behave the same way as Bork.boundStaticFunction().

Babel would emit code either like

Bork.boundStaticFunction = function () {
  return this.staticProperty;
}.bind(Bork);

or:

Bork.boundStaticFunction = function () {
  return Bork.staticProperty;
}

Actual results

Calling (Bork.boundStaticFunction)() results in an error:

Cannot read property 'staticProperty' of undefined

Babel has output this code (literally):

Bork.boundStaticFunction = function () {
  return undefined.staticProperty;
};

Related behavior

Binding an instance property in a similar fashion does work as desired.

Metadata

Metadata

Labels

PR: Spec Compliance 👓A type of pull request used for our changelog categoriesoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions