我希望在我的类中有一个属性是可读的,但不能被类外部的代码直接修改。基本上,等同于从 C++ 中的方法返回对成员的 const 引用。
按照这些思路写一些东西:
class test {
private readonly x_ = new Uint8Array([0, 1, 2]);
public x() { return this.x_;}
}
不起作用,因为像下面这样的代码仍然可以编译:
let a = new test();
a.x()[0] = 1;
实现此目标的正确方法是什么?
最佳答案
对于 future 的读者,我们可以使用 getter
允许在类外读取属性,但限制编辑。
class Test {
private x_ = new Uint8Array([0, 1, 2]);
get x() {
return this.x_;
}
}
let test = new Test();
console.log(test.x) //Can read
test.x = 1; //Error: Cannot assign to 'x' because it is a read-only property.
关于typescript - 在类外只读,但对类成员可读写的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40650031/