class定义私有属性和私有方法

私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。
但 ES6 不提供,只能通过变通方法模拟实现

下面是私有方法和私有属性暴露的例子

  class Foo {
    //公有方法
    foo (baz) {
      this._bar(baz);
    }

    //私有方法
    _bar(baz) {
      return this.baz = baz;
    }
  }

  const instance = new Foo();
  instance.foo(1);
  instance.baz; //1
  instance._bar(2); //2
  instance.baz; //2

解决方案一
将私有方法移出模块,因为模块内部的所有方法都是对外可见的

  class Foo {
    // 公有方法
    foo(baz) {
      _bar.call(this, baz);
    }
  }

  function _bar(baz) {
    return this.baz = baz;
  }

  const instance = new Foo();
  instance.foo(1); 
  instance; //{baz: 1}
  instance._bar(); //Uncaught TypeError: instance1.bar is not a function

解决方法二
利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。

  const bar = Symbol('bar');
  const baz = Symbol('baz');

  export default class Foo {
    //公有方法
    foo (baz) {
      this[bar](baz);
    }

    //私有方法
    [bar](baz) {
      return this[baz] = baz;
    }
  }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值