[英]Getter and setter without members
我們可以在不為成員定義方法的情況下使用 getter 和 setter 嗎?
例如,轉換這個
class int {
set value(val) {
this._value = val | 0; // Truncate
}
get value() {
return this._value;
}
}
var x = new int();
x.value = 5 / 2;
console.log(x.value); // shows 2 instead of 2.5
像這樣:
class int {
set (val) {
this = val | 0; // Truncate
}
get () {
return this;
}
}
var x = new int();
x = 5 / 2;
console.log(x); // shows 2 instead of 2.5
當變量的值(在您的情況下為x
)被替換為新值時,您無法進行任何操作。 這不是 JavaScript 所擁有的。 即使使用代理,您也無法做到這一點。
您對int
第一個定義可能與您將要得到的一樣接近。
人們已經嘗試了各種方法來獲得類似原始類型的東西,比如int
。 他們沒有一個是真正令人滿意的。 例如,這是一個並不少見的嘗試:
class Int {
constructor(value) {
Object.defineProperty(this, "value", {
value: value | 0,
enumerable: true
});
}
set(value) {
return new this.constructor[Symbol.species](value);
}
valueOf() {
return this.value;
}
toString() {
return this.value; // Even though it's not a string
}
static get [Symbol.species]() {
return this;
}
}
然后:
let n = new Int(5);
console.log(`n = ${n}`); // n = 5
n = n.set(n / 2);
console.log(`n = ${n}`); // n = 2
但是一旦你做一些不強制原始的事情,比如:
console.log(n);
你會看到它的客觀性。 你必須要做:
console.log(+n);
這使它成為一個非常大的槍,盡管不變性有助於諸如let m = n
..
例子:
class Int { constructor(value) { Object.defineProperty(this, "value", { value: value | 0, enumerable: true }); } set(value) { return new this.constructor[Symbol.species](value); } valueOf() { return this.value; } toString() { return this.value; // Even though it's not a string } static get [Symbol.species]() { return this; } } let n = new Int(5); console.log(`n = ${n}`); // n = 5 n = n.set(n / 2); console.log(`n = ${n}`); // n = 2 // But console.log(n); // (object representation of it)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.