JavaScript 私有属性 – 3

曾经记录过通过构造函数参数闭包实现的私有属性,不过这种方式依然有局限性。

现通过 ES4 经典方法构造私有属性,展示完整权限控制方案。

//jsfiddle.net/ZenZing/vtr8n902/embed/js/dark/


不过这么做也存在一个缺陷,无法在构造体内实例化自身(self)。解决方法是,把 self 放到构造函数 $ 内,对其他方法传递 self,稍微包装后即可。

;
const MyClass = (function() {
  'use strict';

  const self = {
    // private static const
    get app() {
      return 'ID Card';
    }
  };

  const $ = function () {
    // private
    self.name = '严文';
    // private const
    self.__defineGetter__('age', function () {
      return 21;
    });

    // public
    this.hobby = 'Web Developer';
    this.email = 'i@yanwen.email';
  };

  // public static
  $.modifiedAt = Date();

  // public
  $.prototype.intro = function () {
    console.log(`My name is ${
      self.name
    }, I am ${
      self.age
    } years old ${
      this.hobby
    }. E-Mail: ${
      this.email
    }`);
  };

  return $;
}());

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s