JavaScript 中创建私有成员

目录
  • 1.使用闭包
  • 2.使用 ES6 类
  • 3.使用 ES2020 提案
  • 4.使用 WeakMap
  • 5.使用 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 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 中创建私有成员的文章就介绍到这了,更多相关JavaScript 中创建私有成员内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 基于JavaScript如何实现私有成员的语法特征及私有成员的实现方式

    前言 在面向对象的编程范式中,封装都是必不可少的一个概念,而在诸如 Java,C++等传统的面向对象的语言中, 私有成员是实现封装的一个重要途径.但在 JavaScript 中,确没有在语法特性上对私有成员提供支持, 这也使得开发人员使出了各种奇技淫巧去实现 JS 中的私有成员,以下将介绍下目前实现 JS 私有成员特性的几个方案以及它们之间的优缺点对比. 现有的一些实现方案 约定命名方案 约定以下划线'_'开头的成员名作为私有成员,仅允许类成员方法访问调用,外部不得访问私有成员.简单的代码如下:

  • JavaScript中的私有成员

    JavaScript是世界上是被误解得最厉害的编程语言.有些人认为它不具备"信息隐藏"的能力,因为JavaScript的对象没有私有变量和方法.这是误解.JavaScript对象可以拥有私有成员,下面我们来看看怎么做.(SharkUI.com注:JavaScript并不是真正拥有私有.公有等等OOP的特性,这篇译文中提到的这些私有.公有.特权等特性,是利用JavaScript的其他特性(参看本文的"闭包"一节)"模拟"出来的.感兴趣的话可以搜索相

  • 探索JavaScript中私有成员的相关知识

    坑 首先挖个坑 -- 这是一段 JS 代码,BusinessView 中要干两件事情,即对表单和地图进行布局. 代表将 _ 前缀约定为私有 class BaseView { layout() { console.log("BaseView Layout"); } } class BusinessView extends BaseView { layout() { super.layout(); this._layoutForm(); this._layoutMap(); } _layo

  • JavaScript 私有成员分析

    对象 JavaScript操作都是关于对象的.数组(Array)是对象,函数(Function)是对象.Object(类型)是对象.那么什么是对象呢?对象就是"名称-值"对(name-value).名称是字符串,值可以是字符串.数值.布尔值或对象(包括数组和函数).对象经常用哈希表实现,所以取值速度很快. 如果对象的一个值是函数(function),我们可以认为它是成员函数,当成员函数被调用时,this变量就会指向该对象.成员函数可以通过this变量访问对象的成员. 对象可以通过构造器

  • JavaScript 中创建私有成员

    目录 1.使用闭包 2.使用 ES6 类 3.使用 ES2020 提案 4.使用 WeakMap 5.使用 TypeScript 前言: 面向对象编程语言中的 private 关键字是一个访问修饰符,可用于使属性和方法只能在声明的类中访问.这使得隐藏底层逻辑变得容易,这些底层逻辑应该被隐藏起来,并且不应该与类的外部交互. 但是如何在 JavaScript 中实现类似的功能呢? 没有保留关键字 private ,但在新的标准中 JavaScript 有自己的方法来创建类私有成员,但目前还处于 ES

  • javascript中定义私有方法说明(private method)

    一度以为在javascript的世界里,所有方法都是公有的,无法真正从技术上定义一个私有方法,今天又一次发现:其实我错了! 复制代码 代码如下: var Person = function(name,sex){     this.name = name;     this.sex = sex;          var _privateVariable = "";//私有变量         //构造器中定义的方法,即为私有方法     function privateMethod()

  • 如何在JavaScript中创建具有多个空格的字符串?

    通过创建变量 var a = 'something' + '                         ' + 'something' 我得到这个值:'something something'. 如何在JavaScript中创建一个包含多个空格的字符串? 使用\xa0- 它是一个NO-BREAK SPACE char. 从UTF-8编码表和Unicode字符引用,可以写成如下: var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + '

  • JavaScript中 创建动态 QML 对象的方法

    一.动态创建对象 有两种方法可以从 JavaScript 动态创建对象: 调用 Qt.createComponent() 动态创建 Component 对象 使用 Qt.createQmlObject() 从 QML 字符串创建对象 虽然动态创建的对象可以与其他对象一样使用,但它们在 QML 中没有 id. 1.1.动态创建组件 可以调用它的 createObject() 方法来创建该组件的一个实例.这个函数可以接受两个参数: 第一个是新对象的父对象.父对象可以是图形对象(即 Item 类型)或

  • JavaScript 面向对象的 私有成员和公开成员

    其实很简单,废话少说,看了下面的代码及注释相信你就会一目了然! 复制代码 代码如下: //声明类,就是一个方法,其实在JavaScript中,命名空间.类.成员.... 一切皆对象 MyClass =function(){ var _this=this; //私有变量 var aa="11"; //公开变量 this.bb="22"; //私有方法 function fun1(){ alert(aa); alert(_this.bb); } //私有方法 var f

  • JavaScript中的私有/静态属性介绍

    •模拟块级作用域 大家都知道在JavaScript中没有块级作用域的概念,我们可以通过使用闭包来模拟实现块级作用域,看下面的示例: 复制代码 代码如下: (function () { for (var i = 0; i < 10; i++) { //Do Nothing } alert(i); //输出10 })(); 第6行可以访问到for循环块中的变量i,如果我们稍微修改以上代码,把for循环块放置在闭包中,情况就不一样了: 复制代码 代码如下: (function () { (functi

  • Javascript 中创建自定义对象的方法汇总

    Javascript 中创建对象,可以有很多种方法. Object构造函数/对象字面量: 抛开设计模式不谈,使用最基本的方法,就是先调用Object构造函数创建一个对象,然后给对象添加属性. 复制代码 代码如下: var student = new Object();      student.name = "xiao ming";      student.age = 20;      student.getName = function () {          alert(th

  • 如何在JavaScript中实现私有属性的写类方式(一)

    之前讨论过JavaScript中的写类方式.但没有讨论私有的实现.这篇看下. 我们知道JS中私有属性的实现本质就是 var + closure.如下 复制代码 代码如下: function Person(n, a){     // public     this.name = n;     // private     var age = a;     this.getName = function(){         return this.name;     }     this.getA

随机推荐