无法设置 属性 ... 只有 Getter (javascript es6)
Cannot Set Property ... Which Only Has Getter (javascript es6)
所以我有一个简单的Javascriptclass
class MyClass {
constructor(x) {
this.x = x === undefined ? 0 : x;
}
get x() {
return this.x;
}
}
创建 MyClass 时,我希望将其 x 设置为作为参数传入的值。在此之后,我不希望它能够改变,所以我有意没有制作一个set x()方法。
但是,我想我一定遗漏了一些基本的东西,因为这给了我 "Cannot set property ... which only has getter" 错误。
如何在不创建 setter 方法的情况下为 x 赋值?
class MyClass
{
constructor(x) {
this.x = x === undefined ? 0 : x;
}
get() {
return this.x;
}
set(x) { return this.x = x;}
}
这里有几个问题。
当您通过 get x()
创建 getter 时,您会导致 this.x
导致调用 getter,由于您的 get x()
做 this.x
.
在这段代码中用 this._x
替换你对 this.x
的引用,如下所示:
class MyClass {
constructor(x) {
this._x = x === undefined ? 0 : x;
}
get x() {
return this._x;
}
}
现在您封装的 x
现在是 _x
将不会与通过 this.x
.
调用 getter 混淆
如果您想在 class 定义中创建一个不可变的 属性 a
,os 一种使用方法 JavaScript 的方法给出的是这样做(使用Object.defineProperty()
)。
class MyClass {
constructor(x) {
Object.defineProperty(this, 'a', {
enumerable: false,
configurable: false,
writable: false,
value: x || 'empty'
});
}
}
let o = new MyClass('Hello');
console.log(o.a);
o.a = 'Will not change';
console.log(o.a);
如果您希望实例 属性 为只读,则使其不可写:
class MyClass {
constructor(x) {
Object.defineProperty(this, "x", { value: x || 0 });
}
}
A 属性 可以是 "simple" 属性,因为所有属性都在过去,也可以是 getter/setter 属性。
当 属性 是 getter/setter 属性 时, 所有 对 属性 的引用通过 getter 或 setter、 包括 getter 和 setter 函数中的 。因此,要存储 属性,您需要使用替代的 属性 名称或(更好)Symbol 实例。
所以我有一个简单的Javascriptclass
class MyClass {
constructor(x) {
this.x = x === undefined ? 0 : x;
}
get x() {
return this.x;
}
}
创建 MyClass 时,我希望将其 x 设置为作为参数传入的值。在此之后,我不希望它能够改变,所以我有意没有制作一个set x()方法。
但是,我想我一定遗漏了一些基本的东西,因为这给了我 "Cannot set property ... which only has getter" 错误。
如何在不创建 setter 方法的情况下为 x 赋值?
class MyClass
{
constructor(x) {
this.x = x === undefined ? 0 : x;
}
get() {
return this.x;
}
set(x) { return this.x = x;}
}
这里有几个问题。
当您通过 get x()
创建 getter 时,您会导致 this.x
导致调用 getter,由于您的 get x()
做 this.x
.
在这段代码中用 this._x
替换你对 this.x
的引用,如下所示:
class MyClass {
constructor(x) {
this._x = x === undefined ? 0 : x;
}
get x() {
return this._x;
}
}
现在您封装的 x
现在是 _x
将不会与通过 this.x
.
如果您想在 class 定义中创建一个不可变的 属性 a
,os 一种使用方法 JavaScript 的方法给出的是这样做(使用Object.defineProperty()
)。
class MyClass {
constructor(x) {
Object.defineProperty(this, 'a', {
enumerable: false,
configurable: false,
writable: false,
value: x || 'empty'
});
}
}
let o = new MyClass('Hello');
console.log(o.a);
o.a = 'Will not change';
console.log(o.a);
如果您希望实例 属性 为只读,则使其不可写:
class MyClass {
constructor(x) {
Object.defineProperty(this, "x", { value: x || 0 });
}
}
A 属性 可以是 "simple" 属性,因为所有属性都在过去,也可以是 getter/setter 属性。
当 属性 是 getter/setter 属性 时, 所有 对 属性 的引用通过 getter 或 setter、 包括 getter 和 setter 函数中的 。因此,要存储 属性,您需要使用替代的 属性 名称或(更好)Symbol 实例。