<
>

JavaScript 中创建私有成员

2022-04-16 04:38:45 来源:易采站长站 作者:

目录
1.使用闭包2.使用 ES6 类3.使用 ES2020 提案4.使用 WeakMap5.使用 TypeScript

前言:

面向对象编程语言中的 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 ButtonCrblic 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'.

总结:

暂时禁止评论

微信扫一扫

易采站长站微信账号