博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javascript封装_这是一些具有封装的实用JavaScript对象
阅读量:2523 次
发布时间:2019-05-11

本文共 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)

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/

你可能感兴趣的文章
linux 命令(9) top
查看>>
Android消息处理(一)进程内通信
查看>>
利用office2010 word2010生成目录
查看>>
[ffmpeg 扩展第三方库编译系列] 关于libvpx mingw32编译问题
查看>>
虚拟现实技术对人类是福还是祸?
查看>>
P3106 GPS的决斗
查看>>
hdoj1164
查看>>
简单工厂模式
查看>>
Using关键字的用法
查看>>
标准C程序设计七---60
查看>>
[Silverlight入门系列]使用MVVM模式(4):Prism的NotificationObject自动实现INotifyPropertyChanged接口...
查看>>
工作用工具
查看>>
字符串操作(字符数统计及字符串反转)
查看>>
TexturePacker license Key免费获取方式
查看>>
Android APK反编译
查看>>
两年面试你心得
查看>>
GBK编码相关
查看>>
hdu 1301 Jungle Roads (最小生成树)
查看>>
Java 多态 构造方法
查看>>
ActiveMQ-持久化存储方式
查看>>