在 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
最佳答案
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,它将在原型(prototype)上定义,这当然有一个缺点,即在每次访问属性时都会创建该值:
class Bar {
get() {
return this._value;
}
get _value() {
return 'foo value';
}
}
如果您坚持只使用class
语法,ES2022 will have static blocks这也可能被滥用来创建原型(prototype)属性:
class Bar {
get() {
return this._value;
}
static {
this.prototype._value = 'foo value';
}
}
关于javascript - 使用 Class 声明原型(prototype)默认值的 ecmascript 6 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185643/