千家信息网

JavaScript 中怎样创建私有成员

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,JavaScript 中怎样创建私有成员,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。前言:面向对象编程语言中的 private 关键字
千家信息网最后更新 2026年11月01日JavaScript 中怎样创建私有成员

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 中怎样创建私有成员的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

方法 私有 属性 函数 代码 关键 关键字 变量 闭包 成员 上下 上下文 方式 作用 例子 内容 前缀 功能 参数 实例 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 喔噻互联网科技有限公司 百单网互联网科技有限公司怎么样 科技互联网产品 互联网科技公司税收优惠 金融科技创新监管互联网金融 美国互联网科技 互联网科技公司怎么样 互联网金融 科技创新 互联网科技大会 互联网科技有限公司 翻译 海南科技产业互联网平台 晓花互联网科技有限公司网址 苏州铭阳互联网科技有限公司 国大互联网教育科技有限公司工作 南通创西澳互联网科技有限公司 卡尔迅互联网科技有限公司 九思连强互联网电子科技有限公司 广东鹅鹅鹅互联网科技有限公司 普陀区互联网教育科技管理办法 互联网科技手抄报图片 湖北九亚互联网络科技有限公司 互联网科技活动banner 互联网 科技创业 上海喔噻互联网科技 西安互联网科技公司 辽宁互联网新科技 本届互联网博览会上的黑科技 江苏苏星互联网科技有限公司 美国五大互联网科技公司市值多少 互联网科技创新创业项目
0