search
HomeWeb Front-endJS TutorialDetailed explanation of how to use javascript to encapsulate cookie instances

Before using cookies, they were all operated in the form of document.cookie. Although the compatibility was good, it was troublesome. I personally like to make wheels, so I encapsulated a tool class for cookies. For a long time, I have liked writing code, but I don't really like text summaries, nor do I like writing fragmentary things. It seems that I have to change it.

Ideas

(1) How to encapsulate and what to encapsulate

How to encapsulate: Use native js to encapsulate it into a tool, so that it can be used anywhere use. Encapsulating document.cookie is the best way, and all operations are based on document.cookie.

How to encapsulate it: it can exist in the form of an object, and at the same time, it can be implemented using getter & setter methods.

(2) Which methods are encapsulated?

get(), set(name, value, opts), remove(name), clear(), getCookies(), etc. I personally feel that encapsulation is There are many ways to use cookies.

Action

(1) Understand cookies. The essence of cookies is HTTP cookies. The object displayed on the client is document.cookie. For more information, you can read my code below and comment

(2) Code: These codes should be very intuitive and can be compressed together with the project code. I think the opening comment below is the key point.

/*
 * HTTP Cookie:存储会话信息
 * 名称和值传送时必须是经过RUL编码的
 * cookie绑定在指定的域名下,非本域无法共享cookie,但是可以是在主站共享cookie给子站
 * cookie有一些限制:比如IE6 & IE6- 限定在20个;IE7 50个;Opear 30个...所以一般会根据【必须】需求才设定cookie
 * cookie的名称不分大小写;同时建议将cookie URL编码;路径是区分cookie在不同情况下传递的好方式;带安全标志cookie
 *     在SSL情况下发送到服务器端,http则不会。建议针对cookie设置expires、domain、 path;每个cookie小于4KB
 * */
//对cookie的封装,采取getter、setter方式
(function(global){
    //获取cookie对象,以对象表示
    function getCookiesObj(){
        var cookies = {};
        if(document.cookie){
            var objs = document.cookie.split('; ');
            for(var i in objs){
                var index = objs[i].indexOf('='),
                    name = objs[i].substr(0, index),
                    value = objs[i].substr(index + 1, objs[i].length);    
                cookies[name] = value;
            }
        }
        return cookies;
    }
    //设置cookie
    function set(name, value, opts){
        //opts maxAge, path, domain, secure
        if(name && value){
            var cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
            //可选参数
            if(opts){
                if(opts.maxAge){
                    cookie += '; max-age=' + opts.maxAge; 
                }
                if(opts.path){
                    cookie += '; path=' + opts.path;
                }
                if(opts.domain){
                    cookie += '; domain=' + opts.domain;
                }
                if(opts.secure){
                    cookie += '; secure';
                }
            }
            document.cookie = cookie;
            return cookie;
        }else{
            return '';
        }
    }
    //获取cookie
    function get(name){
        return decodeURIComponent(getCookiesObj()[name]) || null;
    }
    //清除某个cookie
    function remove(name){
        if(getCookiesObj()[name]){
            document.cookie = name + '=; max-age=0';
        }
    }
    //清除所有cookie
    function clear(){
        var cookies = getCookiesObj();
        for(var key in cookies){
            document.cookie = key + '=; max-age=0';
        }
    }
    //获取所有cookies
    function getCookies(name){
        return getCookiesObj();
    }
    //解决冲突
    function noConflict(name){
        if(name && typeof name === 'string'){
            if(name && window['cookie']){
                window[name] = window['cookie'];
                delete window['cookie'];
                return window[name];
            }
        }else{
            return window['cookie'];
            delete window['cookie'];
        }
    }
    global['cookie'] = {
        'getCookies': getCookies,
        'set': set,
        'get': get,
        'remove': remove,
        'clear': clear,
        'noConflict': noConflict
    };
})(window);

(3)example

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>cookie example</title>
    </head>
    <body>
        <script type="text/javascript" src="cookie.js" ></script>
        <script type="text/javascript">
            console.log(&#39;----------cookie对象-------------&#39;);
            console.log(cookie);
            console.log(&#39;----------对象-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------设置cookie-------------&#39;);
            console.log(cookie.set(&#39;name&#39;, &#39;wlh&#39;));
            console.log(&#39;----------设置cookie 123-------------&#39;);
            console.log(cookie.set(&#39;name&#39;, &#39;wlh123&#39;));
            console.log(&#39;----------设置cookie age-------------&#39;);
            console.log(cookie.set(&#39;age&#39;, 20));
            console.log(&#39;----------获取cookie-------------&#39;);
            console.log(cookie.get(&#39;name&#39;));
            console.log(&#39;----------获取所有-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------清除age-------------&#39;);
            console.log(cookie.remove(&#39;age&#39;));
            console.log(&#39;----------获取所有-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------清除所有-------------&#39;);
            console.log(cookie.clear());
            console.log(&#39;----------获取所有-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------解决冲突-------------&#39;);
            var $Cookie = cookie.noConflict(true /*a new name of cookie*/);
            console.log($Cookie);
            console.log(&#39;----------使用新的命名-------------&#39;);
            console.log($Cookie.getCookies());
        </script>
    </body>
</html>

The above is the detailed content of Detailed explanation of how to use javascript to encapsulate cookie instances. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools