js类的get和set特性

 1         class ClassWithGetSet {
 2             #msg = 'hello world';
 3             get msg() {
 4                 // return this.#msg;
 5                 return this.#msg.replace(/w[a-z]+/,'jackal');
 6             }
 7             set msg(x) {
 8                 this.#msg = `hello ${x}`;
 9             }
10         }
11 
12         const instance = new ClassWithGetSet();
13         console.log(instance.msg);
14         // expected output: "hello jackal"
15 
16         instance.msg = 'cake';
17         console.log(instance.msg);
18         // 预期输出值: "hello cake"

这就class中的特性与Object.defineProperty类似

posted @ 2020-09-24 11:15  强者之途  阅读(1060)  评论(0编辑  收藏  举报
/* 看板娘 */