在 JavaScript 中创建私有成员
面向对象编程语言中的 private
关键字是一个访问修饰符,可用于使属性和方法只能在声明的类中访问。这使得隐藏底层逻辑变得容易,这些底层逻辑应该被隐藏起来,并且不应该与类的外部交互。
但是如何在 JavaScript 中实现类似的功能呢? 没有保留关键字 private
,但在新的标准中 JavaScript 有自己的方法来创建类私有成员,但目前还处于 ES2020 试验草案中,并且语法比较奇怪,以 #
作为前缀。下面介绍几种在 JavaScript 代码中实现私有属性和方法的方式。
使用闭包
使用闭包可以使用私有属性或者方法的封装。利用闭包可以访问外部函数的变量特征。如下代码片段:
function MyProfile() { const myTitle = "DevPoint"; return { getTitle: function () { return myTitle; }, }; } const myProfile = MyProfile(); console.log(myProfile.getTitle()); // DevPoint
这可以转化为将最顶层的自调用函数调用分配给一个变量,并且只用函数返回来公开它的一些内部函数:
const ButtonCreator = (function () { const properties = { width: 100, height: 50, }; const getWidth = () => properties.width; const getHeight = () => properties.height; const setWidth = (width) => (properties.width = width); const setHeight = (height) => (properties.height = height); return function (width, height) { properties.width = width; properties.height = height; return { getWidth, getHeight, setWidth, setHeight, }; }; })(); const button = new ButtonCreator(600, 360); console.log(button.getHeight()); // 360
使用 ES6 类
为了使代码更类似于 OOP 方法,可以使用 ES6 中引入的 class
关键字。要使属性和方法私有,可以在类之外定义它们。就对上面的 ButtonCreator
的例子使用 class
进行重构:
const properties = { width: 100, height: 50, }; class ButtonCreator { constructor(width, height) { properties.width = width; properties.height = height; } getWidth = () => properties.width; getHeight = () => properties.height; setWidth = (width) => (properties.width = width); setHeight = (height) => (properties.height = height); } const button = new ButtonCreator(600, 360); console.log(button.getHeight()); // 360
现在假设属性是公共的,但想在私有方法中使用它们,其中上下文指向 ButtonCreator
,可以通过以下方式实现它:
const privates = { calculateWidth() { return this.width; }, }; class ButtonCreator { constructor(width, height) { this.width = width; this.height = height; } getWidth = () => privates.calculateWidth.call(this); getHeight = () => this.height; setWidth = (width) => (this.width = width); setHeight = (height) => (this.height = height); } const button = new ButtonCreator(600, 360); console.log(button.getHeight()); // 360
上面的代码使用了 Function.prototype.call,它用于调用具有给定上下文的函数。在例子中,使用 ButtonCreator
类的上下文。如果私有函数也需要参数,可以将它们作为附加参数传递以调用:
const privates = { calculateWidth(percent) { return this.width * percent; }, }; class ButtonCreator { constructor(width, height) { this.width = width; this.height = height; } getWidth = () => privates.calculateWidth.call(this, 0.1); getHeight = () => this.height; setWidth = (width) => (this.width = width); setHeight = (height) => (this.height = height); } const button = new ButtonCreator(600, 360); console.log(button.getWidth()); // 60
使用 ES2020 提案
还处于 ES2020 试验草案中,引入了私有方法或者属性的定义,语法比较奇怪,以 #
作为前缀。
class ButtonCreator { #width; #height; constructor(width, height) { this.#width = width; this.#height = height; } // 私有方法 #calculateWidth() { return this.#width; } getWidth = () => this.#calculateWidth(); getHeight = () => this.#height; setWidth = (width) => (this.#width = width); setHeight = (height) => (this.#height = height); } const button = new ButtonCreator(600, 360); console.log(button.width); // undefined console.log(button.getWidth()); // 600
使用 WeakMap
这种方法建立在闭包方法之上,使用作用域变量方法创建一个私有 WeakMap
,然后使用该 WeakMap
检索与此相关的私有数据。这比作用域变量方法更快,因为所有实例都可以共享一个 WeakMap
,所以不需要每次创建实例时都重新创建方法。
const ButtonCreator = (function () { const privateProps = new WeakMap(); class ButtonCreator { constructor(width, height, name) { this.name = name; // 公共属性 privateProps.set(this, { width, // 私有属性 height, // 私有属性 calculateWidth: () => privateProps.get(this).width, // 私有方法 }); } getWidth = () => privateProps.get(this).calculateWidth(); getHeight = () => privateProps.get(this).height; } return ButtonCreator; })(); const button = new ButtonCreator(600, 360); console.log(button.width); // undefined console.log(button.getWidth()); // 600
这种方式对于私有方法的使用有点别扭。
使用 TypeScript
可以将 TypeScript
用作 JavaScript 的一种风格,可以使用 private
关键字从面向对象的语言中真正重新创建功能。
class ButtonCreator { private width: number; private height: number; constructor(width: number, height: number) { this.width = width; this.height = height; } private calculateWidth() { return this.width; } public getWidth() { return this.calculateWidth(); } public getHeight() { return this.height; } } const button = new ButtonCreator(600, 360); console.log(button.getWidth()); // 600 console.log(button.width); // error TS2341: Property 'width' is private and only accessible within class 'ButtonCreator'.
总结
本文总结了再 JavaScript 创建私有属性的几种方法,看个人喜欢。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
中国建成全球超70%5G基站,美国却进度缓慢,厘米波技术被卡脖子
在华为等企业的助力下,我国在5G方面已经遥遥领先,掌握到先进技术之后,便开始进行大范围5G基站的建设,根据相关信息,到今年9月份,我国已经建成了115万座基站,在全球5G基站中的占比超70%,稳居世界第一的位置。 不仅如此在我国庞大人口的支持下,其终端用户数量也已经超过了4.5亿,在全球总用户数量中的占比超过了80%,所以说现在无论是基站规模还是用户数量,我国都妥妥的稳居全球首位。 按照当前的这种发展趋势,我国也做出了明确的发展计划,那就是在今后不仅需要始终保持领先之位,同时到2035年时,其境内的5G基站数量需要达到了360万座,由此也可以看出我国对于5G的发展还是充满信心的。 而让人比较意外的是,在我国保持高速发展的过程中,美国的进度却尤为缓慢,连剩下30%的市场份额也没有完全占据,这样的实力也不禁让人怀疑,美国还是世界科技大国吗? 要知道在4G的时候,美国就抢先掌握了技术,在当时4G时代也是属于美国的时代,但到了5G,美国却呈现出了不一样的发展状态。 在5G的建设过程中,有两个频率选择范围,其分别是厘米波技术与毫米波技术,这两个技术各有各的优势,其中毫米波技术拥有不错的传输速度,...
- 下一篇
Easy_Trans 1.1.6 版本发布,一个注解搞定字典/外键翻译
1、升级内容 A 新增枚举翻译 配置type=TransType.ENUM 并且指定key 为desc 则会把 枚举的desc字段返回给前端 @Trans(type=TransType.ENUM,key = "desc") private StudentType studentType = StudentType.ARTS; public static enum StudentType{ ARTS("文科"), SCIENCES("理科"); private String desc; StudentType(String desc){ this.desc = desc; } } 2、介绍 在项目开发中,借助JPA和Mybatis Plus我们已经可以做到单表查询不写SQL,但是很多时候我们需要关联字典表,关联其他表来实现字典码和外键的翻译,又要去写sql,使用 EasyTrans 你只需要在被翻译的pojo属性上加一个注解即可完成字典码/外键 翻译。 先看效果: easy trans适用于三种场景 1 我有一个id,但是我需要给客户展示他的ti...
相关文章
文章评论
共有0条评论来说两句吧...