JavaScript encapsulation for Cookie operations _ javascript skills

Source: Internet
Author: User
Through this article, you can understand that the JavaScript generated by the closure of anonymous functions implements private and public access to document. cookie operation Javascript does not have private and public access permission setting keywords, but you can use certain techniques to simulate the same results.
First, let's look at the following line of code:
Var I = (1, 2, 3, 4, 5 );
The final result of variable I is 5.
This is the result of the comma operator. That is to say, the last value is returned. Parentheses change the priority of this line of code. Otherwise, var I = 1, 2, 3, 4, 5; an error is returned with a missing identifier.


Var I = (1, 2, 3, 4, function () {return 5*5 ;});
The final result of variable I is a function and Result 25 is returned.
This is the flexibility of Javascript. It can assign values of any type without being declared in advance. Now we can make the following calls:

I ();
Alert (I ());
To obtain a method call that returns 25.


The variable I is used to obtain the reference of the function, that is, the reference to the last result returned after the parentheses on the right of the equal sign are still present, although we cannot display the call, but it does exist. What if it is not called by referencing variables?

(1, 2, 3, 4, function () {alert (5*5 );})()
After the above code is executed, a message box is displayed, showing 25.
For ease of display, I changed the function in the previous example to a pop-up message box.
Two pairs of parentheses (); the first pair indicates that a result is returned. If the result is a function, the second pair of parentheses is called.
That is to say, an anonymous function is referenced through a pair of parentheses in order to reference it below. This is the call to an anonymous function.
For more use of anonymous functions, refer to reference connections at the end of the document.

The reason for the closure is that the scope is different. The sub-scope references the variables of the parent scope and returns the sub-scope. The parent scope should be destroyed after execution, it is only because the sub-scope always exists and the reference of the parent scope is always held.
Let's look at the following code:

The Code is as follows:


Function parent (){
Var a = 1;
Function child (){
Var B = 2;
Alert ();
Alert (B );
}
}


The parent function parent contains a child sub-function, which has a reference to the variable in the parent function (output value ).
Let's let the parent function return the declared sub-function after execution.

The Code is as follows:


Function parent (){
Var a = 1;
Function child (){
Var B = 2;
Alert ();
Alert (B );
}
Return child;
}
Var t = parent ();
T ();


In row 10, we executed the parent function and returned the child function declared in the function. At this time, variable t holds the reference of the returned object (an executable function, we called it in 11 lines of code. the results output 1 and 2 respectively.
Note: Output 2 is because we declare a variable in the sub-function body, while output 1 does not have the corresponding definition variable a in the function body, instead, a reference is made to the variables in the parent function, that is, the variables in the parent scope are referenced.
At this time, the output can be completed, that is, variable a still exists. however, we cannot directly reference it (such as parent. a) because the function has been executed and no reference is available, we can only access it through the reference of the returned sub-function.
What if I declare other variables in the parent function? The results are the same. The subfunction can be accessed. If the subfunction does not return a reference, we cannot access the subfunction from the External. This forms a closure.

What can closures do? What should you do if you have a variable that you do not want to allow external modifications at will? Use the closure.

The Code is as follows:


MyObj = {}; // declare a global variable, which is the property of a window object (window. myObj)
(Function (){
Var I = 4;
MyObj = {// reference a global variable and assign a value to it
GetI: function () {// get method, a function
Return I;
},
SetI: function (val) {// set method, restriction Value Setting
If (val> 100 ){
Alert ("I connnt> 100 ");
Return;
}
I = val;
}
}
}) (); // Call an anonymous function. Because it is also a function, as a subscope, it is destroyed after execution to avoid code contamination.
MyObj. setI (5); // succeeded
MyObj. setI (101); // failed
Alert (myObj. getI ());
Alert (myObj. I); // error, no such attribute



At this point, we have implemented the public access permission and private access permission (this is what you want to give you, not what you don't want to give you)



On the page, we usually use document. when the cookie attribute is used for access, a new Cookie is created when a new value is assigned to it. A Cookie usually has five attributes: value (stored value), date (UTC time, indicates the expiration time, domain (domain, Cookie owner), Path (subdirectory ).
In normal development, if you only use document. cookie used ument. when a cookie is read, all values are returned, excluding the expiration time, domain, and other information. It can only be set again.
The following code is enclosed in the global Cookie object, and several methods are exposed.
Get: return all cookie strings.
Set: Set the cookie string.
Clear: clears all cookie objects.
GetDayTime: Get the Date object of the specified val day.
Write: Write cookie. The cookie has been reloaded. For details, see the code.
Query: Query cookie. The cookie has been reloaded. For details, see the code.
Update: Modify cookie.
Delete: Delete a cookie.


Code 1-7

The Code is as follows:


Cookie = {};
/*
* The setTime method of the Date object is to set the number of milliseconds since January 1, to the object. The returned data is in milliseconds instead of the original object.
* If the expires attribute is not set for the Cookie, or the expires time is less than the local time, the Cookie will expire during the next browsing.
* The document. cookie object returns a string of all values, excluding expires or other values.
*
*/
(Function (){
Var nDay = 24x60x60*1000;
Var isString = function (v ){
Return typeof v = "string ";
}
Var isArray = function (v ){
Return Object. prototype. toString. apply (v) = "[object Array]";
}
Var isObject = function (v ){
Return v & typeof v = "object ";
}
Var isDate = function (v ){
Return Object. prototype. toString. apply (v) = "[object Date]";
}
Var getTime = function (){
Return new Date (). getTime ();
}
Var trim = function (val ){
Return (val | ""). replace (/^ \ s + | \ s + $/g ,"");
}
Var tryEval = function (val ){
Var Obj, e;
Try {
Obj = eval (val );
} Catch (e ){
Obj = val;
}
Return Obj;
}
Var ObjectToString = function (o ){
Var tstr = "{";
For (var v in o ){
If (isArray (o [v]) {
Tstr + = v + ":" + ArrayToString (o [v]) + ",";
} Else if (isObject (o [v]) {
Tstr + = v + ":" + ObjectToString (o [v]) + ",";
} Else if (isString (o [v]) {
Tstr + = v + ": \" "+ o [v]. toString () + "\",";
} Else {
Tstr + = v + ":" + o [v]. toString () + ",";
}
}
Return tstr. slice (0,-1) + "}";
}
Var ArrayToString = function (o ){
Var tstr = "[";
For (var v in o ){
If (isArray (o [v]) {
Tstr + = ArrayToString (o [v]) + ",";
} Else if (isObject (o [v]) {
Tstr + = ObjectToString (o [v]) + ",";
} Else {
Tstr + = o [v]. toString () + ",";
}
}
Return tstr. slice (0,-1) + "]";
}
Cookie = {
Get: function (){
Return document. cookie;
},
Set: function (val ){
Document. cookie = val;
},
Clear: function (){
Var temp = this. Query ();
Var o;
For (o in temp ){
This. Delete (o );
}
},
GetDayTime: function (val ){
Var texpires = new Date ();
Texpires. setTime (texpires. getTime () + val * nDay );
Return texpires;
},
Write: function (){
/*
* Cookie. Write (Object); Write Object, name: main;
* Cookie. Write (varname, Object); varname: variable name, Object: Write Object;
* Cookie. Write (Object, Date); Object: Write Object, Date: expiration time;
* Cookie. Write (varname, Object, Date); varname: variable name, Object: Write Object, Date: expiration time;
* Cookie. Write (varname, Object, Date, Domain, Path); varname: variable name, Object: Write Object, Date: expiration time, Domain: Domain, Path: subdirectory;
*/
If (arguments. length = 1 ){
Var tvalue = arguments [0];
Var tstr = "";
Var texpires = new Date (); texpires. setTime (texpires. getTime () + 1 * nDay );
If (isArray (tvalue )){
Tstr = ArrayToString (tvalue );
} Else if (isObject (tvalue )){
Tstr = ObjectToString (tvalue );
} Else {
Tstr = tvalue. toString ();
}
Tstr = "main =" + escape (tstr) + "; expires =" + texpires. toGMTString () + ";";
} Else if (arguments. length = 2 ){
Var tname, tvalue, texpires, tstr = "";
If (isDate (arguments [1]) {
Tname = "main ";
Tvalue = arguments [0];
Texpires = arguments [1];
} Else {
Tname = arguments [0];
Tvalue = arguments [1];
Texpires = new Date (); texpires. setTime (texpires. getTime () + 1 * nDay );
}
If (isArray (tvalue )){
Tstr + = ArrayToString (tvalue );
} Else if (isObject (tvalue )){
Tstr + = ObjectToString (tvalue );
} Else {
Tstr = tvalue. toString ();
}
Tstr = tname + "=" + escape (tvalue) + "; expires =" + texpires. toGMTString () + ";";
} Else if (arguments. length = 3 ){
Var tname = arguments [0], tvalue = arguments [1], texpires = arguments [2], tstr = "";
If (isArray (tvalue )){
Tstr = ArrayToString (tvalue );
} Else if (isObject (tvalue )){
Tstr = ObjectToString (tvalue );
} Else {
Tstr = tvalue. toString ();
}
Tstr = tname + "=" + escape (tvalue) + "; expires =" + texpires. toGMTString () + ";";
} Else if (arguments. length = 5 ){
Var tname = arguments [0], tvalue = arguments [1], texpires = arguments [2], tdomain = arguments [3], tpath = arguments [4], tstr = "";
If (isArray (tvalue )){
Tstr = ArrayToString (tvalue );
} Else if (isObject (tvalue )){
Tstr = ObjectToString (tvalue );
} Else {
Tstr = tvalue. toString ();
}
Tstr = tname + "=" + escape (tvalue) + "; expires =" + texpires. toGMTString () + "; domain =" + tdomain + "; path =" + tpath + ";";
}
Alert (tstr );
This. Set (tstr );
},
Query: function (){
/*
* Cookie. Query (); returns an Object consisting of all Cookie values;
* Cookie. Query (string); returns the Object with the specified name; returns undefined if a failure occurs;
* Cookie. Query (string, Object); write the Object with the specified name for the specified Object and return it; otherwise, return undefined;
*/
Var tname = tvalue = "", tright =-1;
Var tstr = this. Get ();
Var tObj = {};
If (arguments. length = 0 ){
Var I = 0;
Do {
Tname = trim (tstr. slice (I, tstr. indexOf ("=", I )));
Tright = tstr. indexOf (";", I );
If (tright =-1 ){
Tvalue = unescape (tstr. slice (tstr. indexOf ("=", I) + 1, tstr. length ));
} Else {
Tvalue = unescape (tstr. slice (tstr. indexOf ("=", I) + 1, tright ));
}
TObj [tname] = tryEval (tvalue );
I = tstr. indexOf (";", I) =-1? -1: tstr. indexOf (";", I) + 1;
} While (I! =-1 );
} Else {
Tname = arguments [0];
If (tstr. indexOf (tname) =-1) return undefined;
Var I = tstr. indexOf (tname );
Tname = trim (tstr. slice (I, tstr. indexOf ("=", I )));
Tright = tstr. indexOf (";", tstr. indexOf (tname) =-1? Tstr. length: tstr. indexOf (";", tstr. indexOf (tname ));
Tvalue = unescape (tstr. slice (tstr. indexOf (tname) + tname. length + 1, tright ));
If (arguments. length = 1 ){
TObj = tryEval (tvalue );
} Else if (arguments. length = 2 ){
TObj = arguments [1];
TObj [tname] = tryEval (tvalue );
}
}
Return tObj;
},
Update: function (){
Return this. Write. apply (this, arguments );
},
Delete: function (){
If (arguments. length = 1 ){
Var varname = arguments [0];
If (this. Query (varname )){
This. Update (varname, "", new Date (1970, 01, 01 ));
}
}
}
}


One of them is the execution of the string eval into an Object, and the function functions of the corresponding string form are obtained from the Object or Array Object, simulating some JSON operations. of course, not all JavaScript objects can be stored, but only some of them are enough.


My understanding is limited. Please give me more advice.
Javascript anonymous functions: http://dancewithnet.com/2008/05/07/javascript-anonymous-function/
Closure of Javascript: http://www.cn-cuckoo.com/wordpress/wp-content/uploads/2007/08/JavaScriptClosures.html
Cookie File Format: http://www.cnblogs.com/sephil/archive/2008/05/06/cookiefmt.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.