The encapsulation of JavaScript to Cookie operations summary _javascript Tips

Source: Internet
Author: User
Tags closure eval local time
Javascript does not have private, public access to the keyword set, but can be a certain skill 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 the variable i is 5.
This is the result of the comma operator, which means that the last value is returned, and the parentheses change the priority of this line of code, otherwise var i = 1, 2, 3, 4, 5; An error is missing the identifier.


var i = (1, 2, 3, 4, function () {return 5 * 5;});
The final result of the variable i is a function, which returns the result 25.
This is the flexibility of JavaScript to be able to assign any type without having to declare it in advance. Now we can make the following call:

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


We continue, the variable i is using the assignment to get the reference to the function, that is, the last result returned after the parentheses on the right side of the equal sign is still in, although we cannot display the call, but does it exist if it is not invoked by reference to the variable?

(1, 2, 3, 4, function () {alert (5 * 5);}) ()
After the code above executes, a message box pops up, displaying 25.
For ease of display, I changed the function of the previous example to a pop-up message box.
Two pairs of parentheses () (); The preceding pair returns a result, if the result is a function, called by the second pair of parentheses.
That is, a reference to an anonymous function occurs through the preceding pair of parentheses to be referenced below. This is a call to an anonymous function.
Use of more anonymous functions can refer to reference connections at the end of the text.

Closures are caused by the different scopes, a child scope refers to a variable of the parent scope, and the child scope is returned, and the parent scope is supposedly destroyed after execution, except that the child scope always exists and has a reference to the parent scope, so it remains.
Look at the following code
Copy Code code as follows:

function parent () {
var a = 1;
function Child () {
var B = 2;
alert (a);
alert (b);
}
}

The parent function contains a child function that has a reference to a variable in the parent function (output its value) in the child function.
Let's get the parent function to return its declared child function after it's done.
Copy Code code as follows:

function parent () {
var a = 1;
function Child () {
var B = 2;
alert (a);
alert (b);
}
return to child;
}
var t = parent ();
T ();

In line 10, we performed the parent function, returning the function child declared inside the function, when the variable T holds the reference to the returned object (which is a function that can be executed at this point), which we call in 11 lines of code. The results are output 1 and 2 respectively.
Note that output 2 is because we declare a variable in a child function, and output 1, we do not have a corresponding definition of variable A in the function body, but rather a reference to a variable in the parent function, that is, a reference to a variable of the parent scope.
And then the output can be completed, that is, the variable a still exists. But we cannot refer directly to it (such as PARENT.A), because the function has been executed, and without its corresponding reference, we can only access it by reference to the child function returned.
What if I declare another variable in the parent function? The result is the same, the child functions can be accessed, and if the child function does not return the corresponding reference, we simply cannot access it from the outside. This forms a closure.

What can closures do? What do you do if you have a variable that you don't want the outside to arbitrarily modify? Then use the closure.
Copy Code code as follows:

myobj = {}; Declares a global variable, which is the property of a Window object (window.myobj)
(function () {
var i = 4;
MyObj = {//reference global variable, assign value to it
Geti:function () {//get method, a function
return i;
},
Seti:function (val) {//set method, setting of limit values
if (val > 100) {
Alert ("I connt > 100");
Return
}
i = Val;
}
}
})(); anonymous function call, because it is also a function, so as a child scope, after the execution of the destruction, to avoid code pollution
Myobj.seti (5); Success
Myobj.seti (101); Failed
Alert (Myobj.geti ());
alert (MYOBJ.I); Error, no this property


So far we have simply implemented the public access and private access rights (also give you want to you, do not give you do not want to give you)



In the page, we usually use the Document.cookie property to access, the new value will create a new cookie, a cookie usually has five attributes: value (stored value), date (UTC format time, on behalf of what time expires, domain (Domain, owner of the cookie), Path (subdirectory).
In normal development, it can be cumbersome to use only the Document.cookie property for access, because you can only assign a value string to it, and after reading the string cut to get the value of the specified variable name. When Document.cookie reads, Returns all the assigned values, not the expiration time, the fields, and so on.
Here is the code, all encapsulated into the cookie global object, exposing several methods.
Get: Put back the specified all cookie strings.
Set: Sets the cookie string.
Clear: Clears all cookie objects.
Getdaytime: Gets the Date object specified from this Val day.
Write: Writes a cookie. has been overloaded. See code for details.
Query: Querying cookies. has been overloaded. See Code.
Update: Modify Cookies.
Delete: Deletes a cookie.


Code 1-7
Copy Code code as follows:

Cookie = {};
/*
* The SetTime method of the Date object is to set the number of milliseconds since 1970-01-01, set to the object, and return the number of milliseconds after that instead of the original object.
* If the cookie does not set the Expires property, or if the expires time is less than the local time, it will expire on the next browse.
* The Document.cookie object returns the string form of all values, not including expires or other.
*
*/
(function () {
var nday = 24 * 60 * 60 * 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); Writes to the object with the name main;
* Cookie.write (varname, Object); VarName: Variable name, object: Write objects;
* Cookie.write (Object, Date); Object: Writing to objects, Date: Expiration time;
* Cookie.write (VarName, Object, Date); VarName: Variable name, object: Write objects, Date: Expiration time;
* Cookie.write (VarName, Object, Date, Domain, Path); VarName: Variable name, object: Write objects, Date: Expiration time, Domain: field, 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], TS TR = "";
if (IsArray (TValue)) {
Tstr = arraytostring (TValue);
else if (IsObject (TValue)) {
Tstr = objecttostring (TValue);
} else {
Tstr = Tvalue.tostring ();
}
Tstr = tname + "=" + Escape (TValue) + "; expires=" + texpires.togmtstring () + ";d omain=" + tdomain + ";p ath=" + Tpath + ";" ;
}
alert (TSTR);
This. Set (TSTR);
},
Query:function () {
/*
* Cookie.query (); Returns an object consisting of all cookie values;
* Cookie.query (string); Returns the object of the specified name; Failure is returned to undefined;
* Cookie.query (string, Object); Writes an object of the specified name to the specified object and returns; Failure is returned to 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 an object from the string eval, and a function function that obtains the corresponding string form from an object or an Array of objects, simulating some of the actions of JSON. Of course, it doesn't store all the JavaScript objects, just to satisfy a part, I've felt enough.


Personal understanding is limited, please give me a lot of advice.
The anonymous function for javascript: http://dancewithnet.com/2008/05/07/javascript-anonymous-function/
JavaScript closures: http://www.cn-cuckoo.com/wordpress/wp-content/uploads/2007/08/JavaScriptClosures.html
Format of Cookie file: http://www.cnblogs.com/sephil/archive/2008/05/06/cookiefmt.html
Related Article

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.