7

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
2
  • ES6 does not have property declarations on classes, only methods. It is a suggestion for ES7 though: github.com/jeffmo/es-class-fields-and-static-properties Commented Dec 9, 2015 at 17:55
  • @TbWill4321: Those don't create prototype properties though Commented Dec 9, 2015 at 17:56

1 Answer 1

5

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';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.