一个 setter 死循环错误·

2022-03-24 10:58:09 +08:00
 cutemurphy2888
class Dep {
constructor(value) {
this.value = value;
}

get value() {
return this.value;
}

set value(newValue) {
this.value = newValue;
}
}

let dep = new Dep("cc");
dep.value='dd';
2955 次点击
所在节点    JavaScript
18 条回复
10bkill1p
2022-03-24 11:17:27 +08:00
用一个中间变量去传,直接修改是会死循环的。
ccyu220
2022-03-24 11:27:27 +08:00
确实第一次见 get set 和参数名写一样的...
faceRollingKB
2022-03-24 11:48:15 +08:00
class Dep {
constructor(value) {
this._value = value;
}

_value
get value() {
return this._value;
}

set value(newValue) {
this._value = newValue;
}
}
lisongeee
2022-03-24 11:50:21 +08:00
js/python 不像 kotlin ,setter/getter 需要手动声明额外的变量保存状态,kotlin setter/getter 内部有一个关键字 field ,无需手动额外声明变量
cutemurphy2888
2022-03-24 11:57:45 +08:00
@lisongeee 那为什么设计者不借鉴一把 /
lisongeee
2022-03-24 13:37:23 +08:00
我不到啊
enchilada2020
2022-03-24 13:41:43 +08:00
哈哈哈楼上对话太逗了
misdake
2022-03-24 13:45:52 +08:00
变量数据总要保存到一个地方,比如_value 这种。setter 里设置到同一个 setter 上肯定不行呀。
DOLLOR
2022-03-24 14:31:37 +08:00
@faceRollingKB
或许用私有变量更好
class Dep {
constructor(value) {
this.#value = value;
}

#value
get value() {
return this.#value;
}

set value(newValue) {
this.#value = newValue;
}
}

let dep = new Dep("cc");
dep.value = 'dd';


@cutemurphy2888
大概因为没几个人在 JS 里写 class 吧。
TWorldIsNButThis
2022-03-24 14:53:43 +08:00
@cutemurphy2888 kotlin 没有 java 或者 js 里的字段,
只有 property 的概念,property 是否对应一个真正的字段是编译器判断
EyeLip
2022-03-24 16:30:59 +08:00
@lisongeee 刀酱?
blu10ph
2022-03-24 16:40:22 +08:00
@cutemurphy2888 我刚才提的需求,上午为什么没有实现?~
magewu1223ll
2022-03-24 16:44:18 +08:00
应该是 get 引起的吧,每次都读取 一读取就触发 get 然后 get 里面又有个读取,然后触发 get 。。。。。。
thinkershare
2022-03-24 16:44:56 +08:00
因为它本来就应该死循环, 设计上这样写就应该死循环!
jadehare
2022-03-24 16:52:05 +08:00
get value 死循环了,this.value = get value(),相当于方法自己调用自己了
lisongeee
2022-03-24 18:41:38 +08:00
@EyeLip 我是虎弟,你,来沈阳,指定没你好果汁吃
volCan0
2022-03-24 19:30:28 +08:00
看看 vue3 的 ref
Opportunity
2022-05-16 18:30:14 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/842537

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX