使用Class声明原型默认值的ECMAScript 6语法

7
在 JavaScript 中创建类时,您可以通过访问函数的 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"

我该如何使用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

ES6在类上没有属性声明,只有方法。不过这是ES7的建议:https://github.com/jeffmo/es-class-fields-and-static-properties - TbWill4321
@TbWill4321:但是它们不会创建原型属性。 - Bergi
1个回答

5

class语法只允许您定义方法,但它仍然只创建一个带有.prototype对象的构造函数。您可以像在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'

当然,您可能只想创建和初始化一个实例属性:
// 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'

另一种常见的解决方案是使用getter,该getter将在原型上定义,当然缺点是每次访问属性时都会创建值:

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

如果您坚持只使用class语法,那么ES2022将会有静态块,这也可以被滥用来创建原型属性:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接