javascript中的setter和getter

javascript中的setter和getter

在js中的类中,变量属性用来存储数据,函数方法用来执行语句,介于二者中间,产生了set和get,既可以存储数据,也可以执行语句

set和get的特点

  • set有且仅有一个参数
  • get不允许有任何参数
  • 如果仅有set,没有get,这个属性就是只写属性
  • 如果仅有get,没有set,这个属性就是一个只读属性

使用场景

  • 类中常量的实现
class Box{
    //   static  const EVENT_ID="Event_Id";  ES6中不支持这种写法
    constructor(){

    }
    static get EVENT_ID(){  //只读
        return "EVENT_ID";
    }
}

console.log(Box.EVENT_ID);
  • 对象属性的设置
 var div = document.querySelector("div");
Object.defineProperties(div, {
    _ {
      writable: true,
      value: 0,
    },
    _height: {
      writable: true,
      value: 0,
    },
    _bgColor: {
      writable: true,
      value: 0,
    },
     {
      enumerable: true,
      set: function (_value) {
        this.style.width =
          _value.toString().indexOf("px") > -1 ? _value : _value + "px";
        this._width = _value;
      },
      get: function () {
        return this._width;
      },
    },
    height: {
      enumerable: true,
      set: function (_value) {
        this.style.height =
          _value.toString().indexOf("px") > -1 ? _value : _value + "px";
        this._height = _value;
      },
      get: function () {
        return this._height;
      },
    },
    bgColor: {
      enumerable: true,
      set: function (_value) {
        this.style.backgroundColor =
          typeof _value === "string"
            ? _value
            : "#" + _value.toString(16).padStart(6, "0");
        this._bgColor = _value;
      },
      get: function () {
        return this._bgColor;
      },
    },
  });

setInterval(function(){
    div.width++;  //相当于   div.width; div.width+=1;   所以先获取get,得到数值0,后加1,然后开始set,传参,存储
    div.height++;
    div.bgColor++;
},100)

原文地址:https://www.cnblogs.com/94-Lucky/p/13498881.html