'ecmascript 6 syntax for declaring prototype default values using Class

When creating classes in javascript, you can set a default value by accessing the function's prototype.

    function Foo() {
    }
    Foo.prototype.get = function() {
        return this._value;
    }
    Foo.prototype._value = 'foo value';
    var foo = new Foo();
    console.log(foo.get()); // logs "foo value"

How can I achieve a similar effect using ecmascript 6 class?

    // this doesn't work
    class Bar {
        get() {
            return this._value;
        }
        // how to declare following default value properly?
        _value: "bar value"
    }
    var bar = new Bar();
    console.log(bar.get()); // logs undefined


Solution 1:[1]

class syntax does only allow you to define methods, but it still just creates a constructor function with a .prototype object. You can set the default value exactly as in ES5:

// this does work
class Bar {
    get() {
        return this._value;
    }
}
Bar.prototype._value = 'foo value';
var bar = new Bar();
console.log(bar.get()); // logs 'foo value'

Of course you might just want to create and initialise an instance property instead:

// this does work
class Bar {
    constructor() {
        this._value = 'foo value';
    }
    get() {
        return this._value;
    }
}
var bar = new Bar();
console.log(bar.get()); // logs 'foo value'

Another solution that has become rather common is to use a getter, which will be defined on the prototype, which of course has the downside that the value is created on every access of the property:

class Bar {
    get() {
        return this._value;
    }
    get _value() {
        return 'foo value';
    }
}

If you insist on using only class syntax, ES2022 will have static blocks which could also be abused to create a prototype property:

class Bar {
    get() {
        return this._value;
    }
    static {
        this.prototype._value = 'foo value';
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1