您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

JavaScript

51自学网 2022-02-21 13:35:41
  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()); // 360

2.使用 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

3.使用 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()); // 600

4.使用 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 中创建私有成员的文章就介绍到这了,更多相关JavaScript 中创建私有成员内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


下载地址:
elementUI组件el-dropdown(踩坑)
TypeScript 映射类型详情
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。