0
点赞
收藏
分享

微信扫一扫

class中的get set

E_topia 2021-09-30 阅读 63
JavaScript

ES6中的class

  • 类的数据类型就是函数 类本身就是指向构造函数
class Point{
}
typeof Point //function
Point === Point.prototype.construcor //true
  • 类的所有方法都定义在prototype属性上面
class Point {
  constructor() {
    // ...
  }

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}

// 等同于

Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};

//可以直接使用Object.assign合并对象
Object.assign(Point.prototype, {
  toString(){},
  toValue(){}
});

getters & setters

可以通过 get 和 set 关键字来定义 getters 和 setters


class People {
    constructor(name) { //构造函数
          this.name = name;
    }
    get name() {
        return this._name.toUpperCase();
    }
    set name(name) {
        this._name = name;
    }
    sayName() {
          console.log(this.name);
    }
}
var p = new People("tom");
console.log(p.name);    //1 TOM
console.log(p._name);    //2 tom
p.sayName();    //3 TOM

主要是要区分 this._name 和 this.name 的区别。因为我们定义了 name 的读写器,而没有定义 _name 的读写器,所以访问这两个属性的结果是不同的。

但是要注意一点,不要这样写:

set name(name) {
    this.name = name;
}

因为给 this.name 赋值的时候会调用 set name ,这样会导致无限递归直到栈溢出。

举报

相关推荐

0 条评论