Home System Tutorial LINUX Comprehensive introduction to object-oriented JavaScript

Comprehensive introduction to object-oriented JavaScript

Mar 14, 2024 pm 03:22 PM
linux linux tutorial Red Hat linux system data access linux command linux certification red hat linux linux 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
Fixed the failure to upload files in Windows Google Chrome Fixed the failure to upload files in Windows Google Chrome Jul 08, 2025 pm 02:33 PM

Have problems uploading files in Google Chrome? This may be annoying, right? Whether you are attaching documents to emails, sharing images on social media, or submitting important files for work or school, a smooth file upload process is crucial. So, it can be frustrating if your file uploads continue to fail in Chrome on Windows PC. If you're not ready to give up your favorite browser, here are some tips for fixes that can't upload files on Windows Google Chrome 1. Start with Universal Repair Before we learn about any advanced troubleshooting tips, it's best to try some of the basic solutions mentioned below. Troubleshooting Internet connection issues: Internet connection

How to add a new disk to Linux How to add a new disk to Linux Jun 27, 2025 am 12:15 AM

The steps to add a new hard disk to the Linux system are as follows: 1. Confirm that the hard disk is recognized and use lsblk or fdisk-l to check; 2. Use fdisk or parted partitions, such as fdisk/dev/sdb and create and save; 3. Format the partition to a file system, such as mkfs.ext4/dev/sdb1; 4. Use the mount command for temporary mounts, such as mount/dev/sdb1/mnt/data; 5. Modify /etc/fstab to achieve automatic mount on the computer, and test the mount first to ensure correctness. Be sure to confirm data security before operation to avoid hardware connection problems.

What is the sudo command and when should I use it? What is the sudo command and when should I use it? Jul 02, 2025 am 12:20 AM

sudo stands for "substituteuserdo" or "superuserdo", allowing users to run commands with permissions of other users (usually root). Its core uses include: 1. Perform system-level operations such as installing software or editing system files; 2. Accessing protected directories or logs; 3. Manage services such as restarting nginx; 4. Modify global settings such as /etc/hosts. When using it, the system will check the /etc/sudoers configuration and verify the user password, provide temporary permissions instead of continuously logging in as root, ensuring security. Best practices include: only when necessary, avoid blindly executing network commands, editing sudoers files with visudo, and considering continuous operations.

How to manage groups on Linux How to manage groups on Linux Jul 06, 2025 am 12:02 AM

To manage Linux user groups, you need to master the operation of viewing, creating, deleting, modifying, and user attribute adjustment. To view user group information, you can use cat/etc/group or getentgroup, use groups [username] or id [username] to view the group to which the user belongs; use groupadd to create a group, and use groupdel to specify the GID; use groupdel to delete empty groups; use usermod-aG to add users to the group, and use usermod-g to modify the main group; use usermod-g to remove users from the group by editing /etc/group or using the vigr command; use groupmod-n (change name) or groupmod-g (change GID) to modify group properties, and remember to update the permissions of relevant files.

How to find my private and public IP address in Linux? How to find my private and public IP address in Linux? Jul 09, 2025 am 12:37 AM

In Linux systems, 1. Use ipa or hostname-I command to view private IP; 2. Use curlifconfig.me or curlipinfo.io/ip to obtain public IP; 3. The desktop version can view private IP through system settings, and the browser can access specific websites to view public IP; 4. Common commands can be set as aliases for quick call. These methods are simple and practical, suitable for IP viewing needs in different scenarios.

What is the code number of Bitcoin? What style of code is Bitcoin? What is the code number of Bitcoin? What style of code is Bitcoin? Jul 22, 2025 pm 09:51 PM

As a pioneer in the digital world, Bitcoin’s unique code name and underlying technology have always been the focus of people’s attention. Its standard code is BTC, also known as XBT on certain platforms that meet international standards. From a technical point of view, Bitcoin is not a single code style, but a huge and sophisticated open source software project. Its core code is mainly written in C and incorporates cryptography, distributed systems and economics principles, so that anyone can view, review and contribute its code.

System requirements to install linux System requirements to install linux Jul 20, 2025 am 03:49 AM

Linuxcanrunonmodesthardwarewithspecificminimumrequirements.A1GHzprocessor(x86orx86_64)isneeded,withadual-coreCPUrecommended.RAMshouldbeatleast512MBforcommand-lineuseor2GBfordesktopenvironments.Diskspacerequiresaminimumof5–10GB,though25GBisbetterforad

How to use the `shutdown` command How to use the `shutdown` command Jul 15, 2025 am 12:26 AM

The shutdown command of Linux/macOS can be shut down, restarted, and timed operations through parameters. 1. Turn off the machine immediately and use sudoshutdownnow or -h/-P parameters; 2. Use the time or specific time point for the shutdown, cancel the use of -c; 3. Use the -r parameters to restart, support timed restart; 4. Pay attention to the need for sudo permissions, be cautious in remote operation, and avoid data loss.

See all articles