首页 > js中get set 的用处体现在哪里?死循环?

js中get set 的用处体现在哪里?死循环?

var cart = {
  _wheels: 4,

  get _wheels () {
    return this._wheels;//Maximum call stack size exceeded
  },

  set _wheels (value) {
    if (value < this._wheels) {
      throw new Error('数值太小了!');
    }
    this._wheels = value;
  }
}
console.log(cart._wheels);
cart._wheels = 1;
console.log(cart._wheels);

建议看看这篇文章:关于JavaScript中Get/Set访问器
然后就是,我把你这段代码复制进我的 VS Code 中时,显示是这样的:

所以,一个好的编辑器能够帮你直接发现问题。


讲道理,你设置的setter和getter明明是wheels,但是你下面取值赋值用的_wheels,压根没用set/get好吧


单纯这样用一个对象达到保护私有变量的目的是办不到的,需要将内容写在一个闭包里面。

var car = (function(){
            var _wheels = 4;

            return {
                setWheels : function(value){
                    if (value < _wheels) {
                      throw new Error('数值太小了!');
                    }
                    _wheels = value;
                },
                getWheels : function(){
                    return _wheels;
                }
            }

        })();

你上述的方法,调用car._wheels的时候实际上是在调用get方法,get方法里的this._wheels又相当于调用了car._wheels,就是死循环

【热门文章】
【热门文章】