创建javascript对象类成员(javascript私有成员分析)

技术JavaScript 中怎样创建私有成员JavaScript 中怎样创建私有成员,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。前言:面向对象编程语言中的

如何在JavaScript中创建私有成员,相信很多没有经验的人都不知所措。因此,本文总结了问题产生的原因及解决方法。希望你能通过这篇文章解决这个问题。

前言:

面向对象编程语言中的private关键字是一个访问修饰符,它可以用来使属性和方法只能在声明的类中访问。这使得隐藏底层逻辑变得很容易,底层逻辑应该是隐藏的,不应该与类的外部交互。

但是如何在JavaScript中实现类似的功能呢?没有保留关键字private,但新标准中JavaScript有自己的方法创建类的私有成员,但还在ES2020实验稿中,语法比较奇怪,以#为前缀。以下是在JavaScript代码中实现私有属性和方法的几种方法。

1.使用闭包

闭包可以用来封装私有属性或方法。闭包可以用来访问外部函数的可变特性。

如下代码片段:

functionMyProfile(){ 0

constmyTitle=' DevPoint

返回{

gettitle : function(){ 0

returnmyTitle

},

};

}

constmyProfile=my profile();

console . log(my profile . gettitle());//这可以转化为将最顶层的自调用函数调用分配给一个变量,并且只用函数返回来公开它的一些内部函数:发展点

const buttoncreator=(function(){ 0

const properties={ 0

宽度:100,

高度:50,

};

const getwidth=()=properties . width;

constGetHeight=()=properties . height;

constsetWidth=(width)=(properties . width=width);

constsetHeight=(高度)=(properties . height=height);

returnfunction(宽度、高度){ 0

properties.width=width

properties.height=height

返回{

getWidth,

通用电气公司

tHeight,
            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); // undefined
console.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); // undefined
console.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()); // 600
console.log(button.width); // error TS2341: Property 'width' is private and only accessible within class 'ButtonCreator'.

看完上述内容,你们掌握JavaScript 中怎样创建私有成员的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/144747.html

(0)

相关推荐

  • 腾讯手机管家,腾讯手机管家跟管家一样吗

    技术腾讯手机管家,腾讯手机管家跟管家一样吗您好,内置版本的腾讯手机管家与腾讯手机管家基本上不会有区别,某些内置版本中会根据实际的厂家,系统环境对手机管家做相对应的优化修改腾讯手机管家。由于android系统的限制,所以内

    生活 2021年10月27日
  • python里turtle画随机点的分布图(python在地图上画路线)

    技术Python如何根据站点列表绘制站坐标全球分布图本篇内容主要讲解“Python如何根据站点列表绘制站坐标全球分布图”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Pytho

    攻略 2021年12月16日
  • Suse11.4 + DB2 10.5fp8 pureScale如何安装部署

    技术Suse11.4 + DB2 10.5fp8 pureScale如何安装部署这篇文章主要为大家展示了“Suse11.4 + DB2 10.5fp8 pureScale如何安装部署”,内容简而易懂,条理清晰,希望能够帮

    攻略 2021年12月4日
  • 十大名木手串,全球十大最名贵木材有哪些

    技术十大名木手串,全球十大最名贵木材有哪些感谢推荐十大名木手串!我个人是很喜欢盘玩木材的,尤其是小叶紫檀。最近迷上了桃木,因为桃木那独有的纹理是非常吸引我的。如下这些就是最世界珍贵的十种木材。一、乌木乌木(阴沉木)兼备木

    生活 2021年11月1日
  • CF1148H Holy Diver

    技术CF1148H Holy Diver CF1148H Holy Diver一、题目
    点此看题
    二、解法
    输入特性要求的做法就应该是移动右端点 \(r\) 然后维护一些东西。
    首先考虑怎么维护 \([

    礼包 2021年10月28日
  • geth、web3.js、JSON RPC、truffle之间是什么关系?

    技术geth, web3.js, JSON RPC, truffle之间的关系是什么geth, web3.js, JSON RPC, truffle之间的关系是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希

    攻略 2021年12月14日