本文共 1984 字,大约阅读时间需要 6 分钟。
javascript封装
was named one of the !
被评为 !
Encapsulation means information hiding. It’s about hiding as much as possible of the object’s internal parts and exposing a minimal public interface.
封装意味着信息隐藏。 这是关于尽可能隐藏对象的内部部分并公开最小的公共接口。
The simplest and most elegant way to create encapsulation in JavaScript is using closures. A closure can be created as a function with private state. When creating many closures sharing the same private state, we create an object.
在JavaScript中创建封装的最简单,最优雅的方法是使用闭包。 可以将闭包创建为具有私有状态的函数。 当创建多个共享同一私有状态的闭包时,我们将创建一个对象。
I’m going to build a few objects that can be useful in an application: Stack, Queue, Event Emitter, and Timer. All will be built using factory functions.
我将构建一些对应用程序有用的对象:堆栈,队列,事件发射器和计时器。 全部将使用工厂功能构建。
Let’s start.
开始吧。
Stack is a data structure with two principal operation: push
for adding an element to the collection, and pop
for removing the most recent element added. It adds and removes elements according to the Last In First Out (LIFO) principle.
堆栈是具有两个主要操作的数据结构: push
用于将元素添加到集合中, pop
用于移除添加的最新元素。 它根据后进先出(LIFO)原理添加和删除元素。
Look at the next example:
看下一个例子:
let stack = Stack();stack.push(1);stack.push(2);stack.push(3);stack.pop(); //3stack.pop(); //2
using a factory function.
使用工厂函数 。
function Stack(){ let list = []; function push(value){ list.push(value); } function pop(){ return list.pop(); } return Object.freeze({ push, pop });}
The stack object has two public methods push()
and pop()
. The internal state can only be changed through these methods.
堆栈对象具有两个公共方法push()
和pop()
。 内部状态只能通过这些方法进行更改。
stack.list; //undefined
I can’t modify directly the internal state:
我无法直接修改内部状态:
stack.list = 0;//Cannot add property list, object is not extensible
You can find more in the book.
您可以在“ 一书中找到更多信息。
For more on applying functional programming techniques in React take a look at .
有关在React中应用函数式编程技术的更多信息,请查看 。
Learn functional React, in a project-based way, with .
通过 ,以基于项目的方式学习功能性React 。
翻译自:
javascript封装
转载地址:http://pcwzd.baihongyu.com/