创建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)

相关推荐

  • vue开发实战常用三大实用功能(vue开发应该用到哪些技术)

    技术Vue开发的常用方法是什么本篇文章为大家展示了Vue开发的常用方法是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。$nextTick()this.$nextTick()将

    攻略 2021年12月20日
  • Python怎么爬取当当网APP数据

    技术Python怎么爬取当当网APP数据本篇文章给大家分享的是有关Python怎么爬取当当网APP数据,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。目标场景

    攻略 2021年10月26日
  • 树莓派如何连接USB摄像头

    技术树莓派如何连接USB摄像头这篇文章主要介绍树莓派如何连接USB摄像头,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!一、用lsusb指令查看一下是否能识别 二、查看/dev设备ls /dev查看

    攻略 2021年11月20日
  • 在这里不得不说一下我们的ADAMoracle预言机

    技术在这里不得不说一下我们的ADAMoracle预言机 在这里不得不说一下我们的ADAMoracle预言机说到预言机,可能很多人都会懵圈,都会疑惑,这是个啥我怎么没听过区块链为什么需要预言机因为预言机可

    礼包 2021年11月13日
  • 如何使用mysqlbinlog备份binlog搭建Binlog Server

    技术如何使用mysqlbinlog备份binlog搭建Binlog Server这篇文章给大家分享的是有关如何使用mysqlbinlog备份binlog搭建Binlog Server的内容。小编觉得挺实用的,因此分享给大

    攻略 2021年10月27日
  • java中在main中写方法(java面试项目技巧)

    技术Java main面试题有哪些本篇内容介绍了“Java main面试题有哪些”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有

    攻略 2021年12月22日