class PrivateKeywordClass {
private value = 1;
}
const obj = new PrivateKeywordClass();
obj.value // compiler error: Property 'value' is private and only accessible within class
'PrivateKeywordClass'
Tuy nhiên, việc kiểm tra compile time có thể dễ dàng bị bỏ qua, bằng cách loại bỏ thông tin kiểu.
const obj = new PrivateKeywordClass();
(obj as any).value // no compile error
Các trường private đảm bảo rằng các thuộc tính được giữ private trong runtime.
class PrivateFieldClass {
#value = 1;
getValue() {
return this.#value;
}
}
const obj = new PrivateFieldClass();
// You can't access '#value' outside of class like this
obj.value === undefined // This is not the field you are looking for.
obj.getValue() === 1 // But the class itself can access the private field!
// Meanwhile, using private field outside a class is a runtime syntax error:
obj.#value
// While trying to access the private fields of another class is a runtime type error:
class Other {
#value;
getValue(obj) {
return obj.#value // TypeError: Read of private field #value from an object which did
// not contain the field
}
}
new Other().getValue(new PrivateKeywordClass());