Javascript 无成员的Getter和setter
我们可以在不为成员定义方法的情况下使用getter和setter吗 例如,将此Javascript 无成员的Getter和setter,javascript,getter-setter,Javascript,Getter Setter,我们可以在不为成员定义方法的情况下使用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 ins
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;
}
}
然后:
但一旦你做了一些不强迫原始的事情,比如:
console.log(n);
你可以看到它的对象性。你必须做到:
console.log(+n);
这使得它成为一个相当大的步兵,尽管不变性有助于像let m=n
这样的事情
例如:
class Int{
构造函数(值){
Object.defineProperty(这个“值”{
值:值| 0,
可枚举:true
});
}
设置(值){
返回新的this.constructor[Symbol.species](值);
}
价值(){
返回此.value;
}
toString(){
返回this.value;//即使它不是字符串
}
静态获取[Symbol.species](){
归还这个;
}
}
设n=newint(5);
console.log(`n=${n}`);//n=5
n=n.set(n/2);
console.log(`n=${n}`);//n=2
//但是
console.log(n);//(它的对象表示)
x=5/2
将完全忽略以前的x
,除非您在中使用了一些愚蠢的东西(可能?)。如果需要自定义逻辑,则必须以某种方式与属性交互
console.log(+n);