您的位置:  首页 > 技术 > 前端 > 正文

在 JavaScript 中创建私有成员

2021-12-06 12:00 https://my.oschina.net/devpoint/blog/5344380 devpoint 次阅读 条评论

在 JavaScript 中创建私有成员

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

但是如何在 JavaScript 中实现类似的功能呢? 没有保留关键字 private ,但在新的标准中 JavaScript 有自己的方法来创建类私有成员,但目前还处于 ES2020 试验草案中,并且语法比较奇怪,以 # 作为前缀。下面介绍几种在 JavaScript 代码中实现私有属性和方法的方式。

使用闭包

使用闭包可以使用私有属性或者方法的封装。利用闭包可以访问外部函数的变量特征。如下代码片段:

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

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

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

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

这种方式对于私有方法的使用有点别扭。

使用 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 创建私有属性的几种方法,看个人喜欢。

  • 0
    感动
  • 0
    路过
  • 0
    高兴
  • 0
    难过
  • 0
    搞笑
  • 0
    无聊
  • 0
    愤怒
  • 0
    同情
热度排行
友情链接