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
What is the main purpose of Linux?What is the main purpose of Linux?Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

Does the internet run on Linux?Does the internet run on Linux?Apr 14, 2025 am 12:03 AM

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

What are Linux operations?What are Linux operations?Apr 13, 2025 am 12:20 AM

The core of the Linux operating system is its command line interface, which can perform various operations through the command line. 1. File and directory operations use ls, cd, mkdir, rm and other commands to manage files and directories. 2. User and permission management ensures system security and resource allocation through useradd, passwd, chmod and other commands. 3. Process management uses ps, kill and other commands to monitor and control system processes. 4. Network operations include ping, ifconfig, ssh and other commands to configure and manage network connections. 5. System monitoring and maintenance use commands such as top, df, du to understand the system's operating status and resource usage.

Boost Productivity with Custom Command Shortcuts Using Linux AliasesBoost Productivity with Custom Command Shortcuts Using Linux AliasesApr 12, 2025 am 11:43 AM

Introduction Linux is a powerful operating system favored by developers, system administrators, and power users due to its flexibility and efficiency. However, frequently using long and complex commands can be tedious and er

What is Linux actually good for?What is Linux actually good for?Apr 12, 2025 am 12:20 AM

Linux is suitable for servers, development environments, and embedded systems. 1. As a server operating system, Linux is stable and efficient, and is often used to deploy high-concurrency applications. 2. As a development environment, Linux provides efficient command line tools and package management systems to improve development efficiency. 3. In embedded systems, Linux is lightweight and customizable, suitable for environments with limited resources.

Essential Tools and Frameworks for Mastering Ethical Hacking on LinuxEssential Tools and Frameworks for Mastering Ethical Hacking on LinuxApr 11, 2025 am 09:11 AM

Introduction: Securing the Digital Frontier with Linux-Based Ethical Hacking In our increasingly interconnected world, cybersecurity is paramount. Ethical hacking and penetration testing are vital for proactively identifying and mitigating vulnerabi

How to learn Linux basics?How to learn Linux basics?Apr 10, 2025 am 09:32 AM

The methods for basic Linux learning from scratch include: 1. Understand the file system and command line interface, 2. Master basic commands such as ls, cd, mkdir, 3. Learn file operations, such as creating and editing files, 4. Explore advanced usage such as pipelines and grep commands, 5. Master debugging skills and performance optimization, 6. Continuously improve skills through practice and exploration.

What is the most use of Linux?What is the most use of Linux?Apr 09, 2025 am 12:02 AM

Linux is widely used in servers, embedded systems and desktop environments. 1) In the server field, Linux has become an ideal choice for hosting websites, databases and applications due to its stability and security. 2) In embedded systems, Linux is popular for its high customization and efficiency. 3) In the desktop environment, Linux provides a variety of desktop environments to meet the needs of different users.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor