In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
JavaScript 中怎样创建私有成员,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
前言:
面向对象编程语言中的 private 关键字是一个访问修饰符,可用于使属性和方法只能在声明的类中访问。这使得隐藏底层逻辑变得容易,这些底层逻辑应该被隐藏起来,并且不应该与类的外部交互。
但是如何在 JavaScript 中实现类似的功能呢? 没有保留关键字 private ,但在新的标准中 JavaScript 有自己的方法来创建类私有成员,但目前还处于 ES2020 试验草案中,并且语法比较奇怪,以 # 作为前缀。下面介绍几种在 JavaScript 代码中实现私有属性和方法的方式。
1.使用闭包
使用闭包可以使用私有属性或者方法的封装。利用闭包可以访问外部函数的变量特征。
如下代码片段:
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()); // 3602.使用 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()); // 603.使用 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); // undefinedconsole.log(button.getWidth()); // 6004.使用 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); // undefinedconsole.log(button.getWidth()); // 600
这种方式对于私有方法的使用有点别扭。
5.使用 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()); // 600console.log(button.width); // error TS2341: Property 'width' is private and only accessible within class 'ButtonCreator'.看完上述内容,你们掌握JavaScript 中怎样创建私有成员的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.