Javascript Convert a class variable to Getter / Setter using Decorators

Any ideas how I can use a decorator to convert a class field to getter / setter? Example:

class Foo:
    @accessor bar = 0;

const foo = new Foo;

Custom behavior should appear, e.g. foo.bar = 1;

I already tried something like

function accessor(target, name, descriptor) {
    let val;

    return {
        set: function(newVal) {
            val = newVal;
            console.log("setter called");
        },
        get: function() { return val; }
    };
}

but it loses its original meaning bar = 0.

+4
source share
1 answer

The class requires the preservation of private property in which the value will be stored.

Since class fields are currently not supported by the suggestion of decorators and a newer transform-decoratorsBabel plugin, an older transform-decorators-legacyBabel plugin should be used instead.

transform-decorators-legacy , get/set accessors , initializer writable . initializer , ​​ :

function accessor(classPrototype, prop, descriptor) {
  if (descriptor.initializer)
    classPrototype['_' + prop] = descriptor.initializer();

  delete descriptor.writable;
  delete descriptor.initializer;

  descriptor.get = function () { return this['_' + prop] };
  descriptor.set = function (val) { this['_' + prop] = val };
}

class Foo {
  @accessor bar = 0;
}

const foo = new Foo ;
foo.bar = 1;

, , (0) set, (1) set.

transform-decorators-legacy spec-compliant, , . TypeScript .

spec- ES6- :

class Foo {
  get bar() { return this._bar };
  set bar(val) { this._bar = val };
}

Foo.prototype._bar = 0;
+1

Source: https://habr.com/ru/post/1692489/


All Articles