参看 MDN 文档和一篇文章

    1. getter :→ https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/get
    2. setter: → https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/set
    3. 一篇文章:→ 属性的 getter 和 setter
    • get 语法将对象属性绑定到查询该属性时将被调用的函数
    • 当尝试设置属性时,set 语法将对象属性绑定到要调用的函数

    gettersetter 实际上是一种调用属性的一种方法,本质上其实是一种函数,因为调用它们的方式和使用属性的方式一模一样,所以也叫做属性,是一种访问器属性。

    1. const user = {
    2. firstName: "Eddie",
    3. lastName: "Ma",
    4. get fullName() {
    5. return this.firstName + " " + this.lastName;
    6. }
    7. };
    8. console.log(user.fullName);
    9. // Eddie Ma

    fullName 就像一个属性一样直接能够访问,它的属性值是计算出来的,当访问 user.fullName 的使用,自动调用了 getter 方法

    这种属性是伪属性,能够直接访问,向如下这样直接修改会报错 user.fullName = "Eddie Peng"

    1. const user = {
    2. firstName: "Eddie",
    3. lastName: "Ma",
    4. get fullName() {
    5. return this.firstName + " " + this.lastName;
    6. }
    7. };
    8. user.fullName = "Eddie Peng";
    9. console.log(user.fullName);
    10. // Uncaught TypeError: Cannot set property fullName of #<Object> which has only a getter

    报错的道理很简单,伪属性的本质上是一个函数,是计算出来的,当然不能直接修改,修改方式自然还是通过函数的方式修改,我们使用 setter

    1. const user = {
    2. firstName: "Eddie",
    3. lastName: "Ma",
    4. get fullName() {
    5. return this.firstName + " " + this.lastName;
    6. },
    7. set fullName(name) {
    8. const array = name.split(" ");
    9. if (array.length === 2) {
    10. this.firstName = array[0];
    11. this.lastName = array[1];
    12. }
    13. }
    14. };
    15. user.fullName = "Eddie Peng";
    16. console.log(user.fullName);
    17. // Eddie Peng

    现在使用 user.fullName = "Eddie Peng" 不会报错了,因为它会自动调用 setter 方法做计算

    我们发现一个道理,gettersetter 本质上都是依赖现有的实属性的,它的设计初衷就是这样

    以下方式可以在一个现有对象上添加一个伪属性

    1. const user = {
    2. firstName: "Eddie",
    3. lastName: "Ma"
    4. };
    5. Object.defineProperty(user, "fullName", {
    6. get() {
    7. return this.firstName + " " + this.lastName;
    8. },
    9. set(name) {
    10. const array = name.split(" ")
    11. if(array.length ===2){
    12. this.firstName = array[0]
    13. this.lastName = array[1]
    14. }
    15. }
    16. });
    17. console.log(user.fullName)
    18. // Eddie Ma
    19. user.fullName = "Eddie Peng"
    20. console.log(user.fullName)
    21. // Eddie Peng

    「@浪里淘沙的小法师」