Skip to content
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

Flow error on using this.x as a default param in a class #1234

Closed
hzoo opened this issue Dec 31, 2015 · 5 comments
Closed

Flow error on using this.x as a default param in a class #1234

hzoo opened this issue Dec 31, 2015 · 5 comments

Comments

@hzoo
Copy link

hzoo commented Dec 31, 2015

This shouldn't be an error right? flow 0.20.0, node 5.1.0

 10:   asdf(str: string = this.b) {
                               ^ property `b`. Property cannot be accessed on
global object
/* @flow */

export default class A {
  constructor() {
    this.b = "";
  }

  b: string;

  asdf(str: string = this.b): string {
    return str;
  }
}
@dasilvacontin
Copy link

this is referencing the current scope during function definition. How would you reference the current scope otherwise? But if then, how do you reference the instance?

@samwgoldman
Copy link
Member

It's very possible I got the scoping wrong on the default expr. I suspect you are right here, but it would be very helpful if you could link to the relevant part of the spec that indicates what this should evaluate to in a class method argument default expr.

@burgalon
Copy link

@Jessidhia
Copy link

Jessidhia commented Aug 3, 2016

A default expression is not evaluated until it is necessary, and will be re-evaluated on every call that needs it. It also does not capture the outer this -- it runs with the same this as the body of the function when evaluated.

I am not entirely sure on the spec language, but I'm trying to follow the definition of [[Call]]. By the time the default expression evaluation at FunctionDeclarationInstantiation.28 happens (called from OrdinaryCallEvaluateBody), the OrdinaryCallBindThis has already happened. The defaults should see the same this as the function body.

This, of course, still allows it to be either global (in sloppy mode) or undefined if you go and extract it and call it as a function, but that is not how you normally use a method declared in a class.

Arrow functions bind their this at declaration time so they would see the declaration scope's this. The appropriate value of this in class property declarations is still being debated, but as of TC39 2016-07 it seemed to lean towards pointing to the new instance being constructed (initialisers are evaluated as if inside a method that is called in the new instance).

@brendan-roche
Copy link

Is there any updates / workarounds on this one?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants