看下面的简单代码,我可以将 "t.map.text.color "设置为 "黄色",而不用".map"。
这怎么可能!?
class Text {
constructor() {
this.map = {};
this.map.text = { color: 'red' }
}
get text() { return this.map.text; }
}
const t = new Text();
t.text.color = 'yellow'; // WHY DOES IT FUNCTION??
console.log(t.map.text.color); // yellow
你得到的是一个 参考 到对象 { color: 'red' }
.getter本质上与编写
getText() {
return this.map.text;
}
因为你的getter函数,指向了this.map.text。
你基本上是在做 t.text()
的指针,返回一个指向 t.map.text
通过这样做 t.text().color
(附 获取者 你可以只做 t.text.color
),你指的是 t.map.text.color
并将其视为 "yellow"
价值