首页 系统教程 操作系统 JavaScript面向对象轻松入门之综合

JavaScript面向对象轻松入门之综合

Mar 14, 2024 pm 03:22 PM
linux linux教程 红帽 linux系统 数据访问 linux命令 linux认证 红帽linux linux视频

JavaScript面向对象轻松入门之综合

需求:

几乎所有的web应用都需要保存数据一些到本地,那么我们就来做一个数据储存器吧。

详细需求:

当本地储存有数据时,取用本地的数据,没有时使用默认的数据
判断本地的数据是否过时,如果过时则不使用
默认使用localStorage,但支持使用其它储存方式,并且要支持多方储存,多方读取

抽象出对象

根据需求里面的关键字,我们抽象出三个对象:数据访问、数据、储存器
数据储存管理器负责管理数据,对外暴露接口
数据对象负责对数据的操作
储存器负责保持数据,读取数据

储存器对象

DataStorageManagerBase暴露两个接口save()和load(),模拟抽象类,告诉子类一定要实现这两个方法。
下面的例子用LocalStorage实现了一个子类,当然你也可以用cookie或其它方式实现。
为什么要把LocalStorage这些储存器进行二次封装呢?直接用不就可以了吗?
因为各种储存器等api都是不一样等,我们二次封装后可以确保无论什么储存器对外暴露的接口都是save()和load()。

/*模拟数据储存器抽象类,其实这个类不要也可以*/
class DataStorageManagerBase {
    static getIns() {
        /* 储存器在整个应用的生命周期里应该只有一个实例 */
        if (!this._ins) this._ins = new this();
        return this._ins;
    }
    constructor() {
        this.name = null;
    }
    save(name/* string */, data/* any */) {
        throw '"' + this.constructor.name + "'类没有save()方法";
    }
    load(name/* string */) {
        throw '"' + this.constructor.name + "'类没有load()方法";
    }
}
class LocalStorageManager extends DataStorageManagerBase {
    static getIns() {
        /* 静态方法不能继承 */
        if (!this._ins) this._ins = new this();
        return this._ins;
    }
    constructor() {
        super();
        this.name = 'localStorage';
    }
    save(name/* string */, data/* any */) {
        console.log(name,data)
        if (!window.localStorage) return this;//判断这个储存器可用不可用,你也可以在这里抛出错误
        window.localStorage[name] = JSON.stringify(data);
        return this;
    }
    load(name/* string */) {
        //如果储存器不可用,返回false
        if (!window.localStorage) return false;
        //如果没有这个数据,返回false
        if (!window.localStorage[name]) return false;
        let dataLoaded = JSON.parse(window.localStorage[name]);
        return dataLoaded;
    }
}
登录后复制
数据对象

对数据的操作:保存、读取、判断版本等

class GlobalData {
    static addStorage(storage/* DataStorageManagerBase */) {
        /*动态添加储存器*/
        this._storages.push();
    }
    static getStorages() {
        return this._storages;
    }
    constructor(name, data, version) {
        this.name = name;
        this.data = data;
        this.version = version || 1;
        this._loadData();
        //初始化的该对象的时候,读取localStorage里的数据,看有没有已储存的数据,有就用该数据
    }
    getData() {
        return this._copy(this.data);
    }
    setData(data, notSave) {
        this.data = this._copy(data);
        if (!!notSave) return this;
        let dataToSave = {
            name: this.name,
            version: this.version,
            data: this.data
        };
        let storages = GlobalData.getStorages();
        for (let i = 0, l = storages.length; i 
<div style="font-size: 14pt; color: white; background-color: black; border-left: red 10px solid; padding-left: 14px; margin-bottom: 20px; margin-top: 20px;"><strong>数据访问对象</strong></div>
<p>对数据对象管理,对外暴露三个接口getData(),setData(),config(),用户通过这三个接口使用这个模块</p>
<pre class="brush:php;toolbar:false">class GlobalDataDao {
    static getIns() {
        if (!this._ins) this._ins = new this();
        return this._ins;
    }
    constructor() {
        this.GlobalDataClass = GlobalData;
        this._dataList = [];
    }
    getData(name/* string */) {
        let dataIns = this.getDataIns(name);
        if (!!dataIns) {
            return dataIns.getData();
        } else {
            return null;
        }
    }
    setData(name/* string */, data/* any */, notSave = false/* ?boolean */) {
        let dataIns = this.getDataIns(name);
        dataIns.setData(data, notSave);
        return this;
    }
    config(configs/* Array */) {
        /* 初始化数据
        interface Config {
            name: string;
            data; any;
            version?: number;
        }
        */
        for (let i in configs) {
            let de = configs[i];
            if (!!this.getDataIns(de.name)) {
                /* 如果数据名重复,抛出错误 */
                throw new Error('data name "' + de.name + '" is exist');
            };
            let dataIns = new GlobalData(de.name, de.data, de.version);
            this._dataList.push(dataIns);
        }
        return this;
    }
    getDataIns(name/* string */) {
        for (let i in this._dataList) {
            if (this._dataList[i].name === name) {
                return this._dataList[i];
            }
        }
        return false;
    }
}
登录后复制
使用
/*用法*/
let globalDataManeger = GlobalDataDao.getIns();

let configs = [
    {
        name: 'languageUsing',
        version: 1,
        data: {
            name: '简体中文',
            value: 'zh-cn'
        }
    }, {
        name: 'userPreference',
        version: 1,
        data: {
            theme: 'blue',
            menu: 'side_bar'
        }
    }
];
globalDataManeger.config(configs);
console.log(globalDataManeger);
let languageUsing = globalDataManeger.getData('languageUsing');
console.log(languageUsing);
languageUsing.name = 'English';
languageUsing.value = 'en';
globalDataManeger.setData('languageUsing', languageUsing);
登录后复制

以上是JavaScript面向对象轻松入门之综合的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

centos和ubuntu的区别 centos和ubuntu的区别 Apr 14, 2025 pm 09:09 PM

CentOS 和 Ubuntu 的关键差异在于:起源(CentOS 源自 Red Hat,面向企业;Ubuntu 源自 Debian,面向个人)、包管理(CentOS 使用 yum,注重稳定;Ubuntu 使用 apt,更新频率高)、支持周期(CentOS 提供 10 年支持,Ubuntu 提供 5 年 LTS 支持)、社区支持(CentOS 侧重稳定,Ubuntu 提供广泛教程和文档)、用途(CentOS 偏向服务器,Ubuntu 适用于服务器和桌面),其他差异包括安装精简度(CentOS 精

centos如何安装 centos如何安装 Apr 14, 2025 pm 09:03 PM

CentOS 安装步骤:下载 ISO 映像并刻录可引导媒体;启动并选择安装源;选择语言和键盘布局;配置网络;分区硬盘;设置系统时钟;创建 root 用户;选择软件包;开始安装;安装完成后重启并从硬盘启动。

Centos停止维护2024 Centos停止维护2024 Apr 14, 2025 pm 08:39 PM

CentOS将于2024年停止维护,原因是其上游发行版RHEL 8已停止维护。该停更将影响CentOS 8系统,使其无法继续接收更新。用户应规划迁移,建议选项包括CentOS Stream、AlmaLinux和Rocky Linux,以保持系统安全和稳定。

CentOS上GitLab的备份方法有哪些 CentOS上GitLab的备份方法有哪些 Apr 14, 2025 pm 05:33 PM

CentOS系统下GitLab的备份与恢复策略为了保障数据安全和可恢复性,CentOS上的GitLab提供了多种备份方法。本文将详细介绍几种常见的备份方法、配置参数以及恢复流程,帮助您建立完善的GitLab备份与恢复策略。一、手动备份利用gitlab-rakegitlab:backup:create命令即可执行手动备份。此命令会备份GitLab仓库、数据库、用户、用户组、密钥和权限等关键信息。默认备份文件存储于/var/opt/gitlab/backups目录,您可通过修改/etc/gitlab

docker原理详解 docker原理详解 Apr 14, 2025 pm 11:57 PM

Docker利用Linux内核特性,提供高效、隔离的应用运行环境。其工作原理如下:1. 镜像作为只读模板,包含运行应用所需的一切;2. 联合文件系统(UnionFS)层叠多个文件系统,只存储差异部分,节省空间并加快速度;3. 守护进程管理镜像和容器,客户端用于交互;4. Namespaces和cgroups实现容器隔离和资源限制;5. 多种网络模式支持容器互联。理解这些核心概念,才能更好地利用Docker。

centos怎么挂载硬盘 centos怎么挂载硬盘 Apr 14, 2025 pm 08:15 PM

CentOS硬盘挂载分为以下步骤:确定硬盘设备名(/dev/sdX);创建挂载点(建议使用/mnt/newdisk);执行mount命令(mount /dev/sdX1 /mnt/newdisk);编辑/etc/fstab文件添加永久挂载配置;卸载设备使用umount命令,确保没有进程使用设备。

Centos停止维护后的选择 Centos停止维护后的选择 Apr 14, 2025 pm 08:51 PM

CentOS 已停止维护,替代选择包括:1. Rocky Linux(兼容性最佳);2. AlmaLinux(与 CentOS 兼容);3. Ubuntu Server(需要配置);4. Red Hat Enterprise Linux(商业版,付费许可);5. Oracle Linux(与 CentOS 和 RHEL 兼容)。在迁移时,考虑因素有:兼容性、可用性、支持、成本和社区支持。

docker desktop怎么用 docker desktop怎么用 Apr 15, 2025 am 11:45 AM

如何使用 Docker Desktop?Docker Desktop 是一款工具,用于在本地机器上运行 Docker 容器。其使用步骤包括:1. 安装 Docker Desktop;2. 启动 Docker Desktop;3. 创建 Docker 镜像(使用 Dockerfile);4. 构建 Docker 镜像(使用 docker build);5. 运行 Docker 容器(使用 docker run)。

See all articles