search
HomeSystem TutorialLINUXComprehensive introduction to object-oriented JavaScript

Comprehensive introduction to object-oriented JavaScript

Mar 14, 2024 pm 03:22 PM
linuxlinux tutorialRed Hatlinux systemdata accesslinux commandlinux certificationred hat linuxlinux video

Comprehensive introduction to object-oriented JavaScript

need:

Almost all web applications need to save some data locally, so let's make a data storage.

Detailed requirements:

When there is data stored locally, the local data is used, and when there is no data, the default data is used
Determine whether the local data is out of date. If it is out of date, do not use
By default, localStorage is used, but other storage methods are supported, and multi-party storage and multi-party reading are supported

Abstract object

According to the keywords in the requirements, we abstract three objects: data access, data, storage
The data storage manager is responsible for managing data and exposing the interface
Data objects are responsible for operating data
The storage is responsible for retaining data and reading data

Storage object

DataStorageManagerBase exposes two interfaces save() and load(), simulates abstract classes, and tells subclasses to implement these two methods.
The following example implements a subclass using LocalStorage. Of course, you can also implement it using cookies or other methods.
Why should LocalStorage be re-encapsulated? Can't you just use it directly?
Because the APIs of various memories are different, after secondary encapsulation, we can ensure that no matter what memory is exposed to the outside world, the interfaces are save() and 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;
    }
}
Data Object

Operations on data: saving, reading, determining version, etc.

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>Data Access Object</strong></div>
<p>For data object management, three interfaces getData(), setData(), and config() are exposed to the outside. Users use this module through these three interfaces</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;
    }
}
use
/*用法*/
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);

The above is the detailed content of Comprehensive introduction to object-oriented JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Linux就该这么学. If there is any infringement, please contact admin@php.cn delete
Warehouse: A GUI for Effortlessly Handling Flatpak AppsWarehouse: A GUI for Effortlessly Handling Flatpak AppsMay 09, 2025 am 11:30 AM

A GUI for Effortless Flatpak Management: Introducing Warehouse Managing a growing collection of Flatpak applications can be cumbersome using only the command line. Enter Warehouse, a user-friendly graphical interface designed to streamline Flatpak a

8 Powerful Linux Commands to Identify Hard Drive Bottlenecks8 Powerful Linux Commands to Identify Hard Drive BottlenecksMay 09, 2025 am 11:03 AM

This article provides a comprehensive guide to identifying and resolving hard drive bottlenecks in Linux systems. Experienced server administrators will find this particularly useful. Slow disk operations can severely impact application performance,

4 Best QR Code Generators for Linux Users4 Best QR Code Generators for Linux UsersMay 09, 2025 am 10:27 AM

Efficient QR code generation tool under Linux system In today's digital world, QR codes have become a way to quickly and conveniently share information, simplifying data access from URLs, texts, contacts, Wi-Fi credentials, and even payment information. Linux users can use a variety of tools to create QR codes efficiently. Let's take a look at some popular QR code generators that can be used directly on Linux systems. QRencode QRencode is a lightweight command line tool for generating QR codes on Linux. It is well-received for its simplicity and efficiency and is popular with Linux users who prefer direct methods. Using QRencode, you can use the URL,

elementary OS 8: A User-Friendly Linux for macOS and Windowselementary OS 8: A User-Friendly Linux for macOS and WindowsMay 09, 2025 am 10:19 AM

Elementary OS 8 Circe: A Smooth and Stylish Linux Experience Elementary OS, a Ubuntu-based Linux distribution, has evolved from a simple theme pack into a fully-fledged, independent operating system. Known for its user-friendly interface, elegant de

40  Linux Commands for Every Machine Learning Engineer40 Linux Commands for Every Machine Learning EngineerMay 09, 2025 am 10:06 AM

Mastering Linux is crucial for any machine learning (ML) engineer. Its command-line interface offers unparalleled flexibility and control, streamlining workflows and boosting productivity. This article outlines essential Linux commands, explained fo

Arch Linux Cheat Sheet: Essential Commands for BeginnersArch Linux Cheat Sheet: Essential Commands for BeginnersMay 09, 2025 am 09:54 AM

Arch Linux: A Beginner's Command-Line Cheat Sheet Arch Linux offers unparalleled control but can feel daunting for newcomers. This cheat sheet provides essential commands to confidently manage your system. System Information & Updates These com

How to Install Scikit-learn for Machine Learning on LinuxHow to Install Scikit-learn for Machine Learning on LinuxMay 09, 2025 am 09:53 AM

This guide provides a comprehensive walkthrough of installing and using the Scikit-learn machine learning library on Linux systems. Scikit-learn (sklearn) is a powerful, open-source Python library offering a wide array of tools for various machine l

How to Install Kali Linux Tools in UbuntuHow to Install Kali Linux Tools in UbuntuMay 09, 2025 am 09:46 AM

This guide explains how to leverage Docker for accessing Kali Linux tools, a safer and more efficient alternative to outdated methods like Katoolin. Katoolin is no longer actively maintained and may cause compatibility problems on modern systems. Do

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)