craigmichaelmartin
craigmichaelmartin

Reputation: 6489

es6 variable scope with extended class and modules

Why does es6 not allow this? I understand that message is only defined in the alert module and is undefined in the base module, but I (apparently wrongly) imagine that since the alert class has access to it, all of the class should... Thoughts?

//file component.js
import Base from './base';
const message = "hello";
class Alert extends Base {
    initialize() {
        this.render();
    }
}
export default Alert;

and

//file base.js
class Base {
    render() {
        alert(message);
    }
}
export default Base;

Upvotes: 0

Views: 923

Answers (2)

Bergi
Bergi

Reputation: 665536

The Base class and it's methods don't have access to any of the variables in the component module, which has its own scope. It could gain access to the exported values if it would import the module, but not to the local message variable.

I think you'll want to use static properties of the class here, to which the Base methods would have access when called on an Alert instance:

import Base from './base';
export default class Alert extends Base {
    initialize() {
        this.render();
    }
}
Alert.message = "hello"; // not constant, though; you'd need to use
                         // Object.defineProperty(Alert, "message", {value: …} for that

export default class Base {
    render() {
        alert(this.constructor.message);
    }
}
Base.message = "";

See also es6 call static methods for how this.constructor.… works.

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817198

This doesn't work because JavaScript has lexical scope, not dynamic scope.

Lexical scope means that whether a variable is accessible or not depends on where they appear in the source text, it doesn't depend on runtime information.

Simplified example:

function foo() {
  var bar = 42;
  baz();
}

function baz() {
  console.log(bar); // error because bar is not in the scope of baz
}

Note: This is not new for classes or ES6, that was always the case.

Upvotes: 1

Related Questions