javascript - setters和getters之谜......为什么它能发挥作用?

问题描述 投票:-1回答:2

看下面的简单代码,我可以将 "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
javascript json getter setter
2个回答
0
投票

你得到的是一个 参考 到对象 { color: 'red' }.getter本质上与编写

getText() {
  return this.map.text;
}

0
投票

因为你的getter函数,指向了this.map.text。

你基本上是在做 t.text() 的指针,返回一个指向 t.map.text

通过这样做 t.text().color (附 获取者 你可以只做 t.text.color),你指的是 t.map.text.color 并将其视为 "yellow" 价值

© www.soinside.com 2019 - 2024. All rights reserved.