Question
目前,我正在嘗試為我的類創建一個只讀值,這樣就沒有人可以編輯這些變量并弄亂類。
在我的類中,唯一的值可以是1、0、true或false,如果它們可以在任何時候編輯任何值,它們就可以將var設置為out-of-scope值,這可能會導致代碼錯誤!
let Bit1 = new Bit(1);
Bit1.Value = "fdgdf" // <-- You Should Not be able to do this!!
...
我想到了一種解決這個問題的方法,就是創建一個允許您更改值的函數,這樣它就不會是out-of-scope。
Bit1.ChangeValue(true) // Accepted Value
Bit1.ChangeValue("agjg") // Should throw Error: "Error: Value has to be ether a 1, 0 or an Boolean"
Bit1.Value = "hbkij" // <-- You should not be able to do this!!
但正如您所見,您仍然可以編輯原始值而不會出錯!
很快,我注意到我需要一個read-only變量,我知道javascript因為MDN而有readOnly變量,但我不知道如何生成只讀變量
Please Help!!
Extra Info
IDE: Codesandbox
Browser: Chrome
Full Code:
class Bit {
/**
*
* @param {(Boolean|Number)} Value A Byte Value (1, 0, true, false)
*/
constructor(Value) {
if (Value !== null) {
if (typeof Value === Boolean) {
this.Value = +Value;
} else if (typeof Number) {
if (Value === 1 || Value === 0) {
this.Value = Value;
} else {
throw new Error("Error: Value has to be ether a 1, 0 or an Boolean");
}
} else {
throw new Error("Error: Value has to be ether a 1, 0 or an Boolean");
}
} else {
throw new Error("Error: Value has to be ether a 1, 0 or an Boolean");
}
}
/**
* @description Swiches the Bit (1 -> 0, 0 -> 1)
*/
Switch() {
this.Value = Boolean(this.Value) ? 0 : 1;
}
}
//class Bytes {
// /**
// *
// * @param {Array} Bits Array Of up to 8 bits (1, 0, true, false, Bit)
// */
// constructor(Bits) {
//
// }
//}
你可以使用
Object.defineProperty(..)
下面是一個例子:
即使
bit.value = ..
沒有任何效果,因為此屬性設置為configurable: true
,它仍然可以使用Object.defineProperty
刪除或編輯。另一種方法是使用setter和getter,下面是一個示例: