Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ES2015 exported class create a closure?

As it's currently compiled via Babel + Webpack, module's exported class will create a closure: variables created inside the module will be shared between class instances.

bar.js:

let foo;

export default class Bar {
    set foo(value) {
        foo = value;
    }
    get foo() {
        return foo;
    }
}

app.js:

import Bar from './bar.js';

var barOne = new Bar();
var barTwo = new Bar();

barOne.foo = 'quux';
console.assert(barTwo.foo === 'quux');

I wonder if this behavour correct according to the spec.

like image 574
Pavlo Avatar asked Sep 06 '25 03:09

Pavlo


1 Answers

I wonder if this behavour correct according to the spec.

Yes. JavaScript has lexical scope. That doesn't change with classes.

Keep in mind that classes are more or less just syntactic sugar for constructor function + prototype. Would you have had the same question if you wrote

let foo;

function Bar(){};

Bar.prototype = {
    set foo(value) {
        foo = value;
    }
    get foo() {
        return foo;
    }
};

module.exports = Bar;

instead?

like image 81
Felix Kling Avatar answered Sep 08 '25 00:09

Felix Kling