function CookieStorage(maxage, path) { // Arguments specify lifetime and scope
// Get an object that holds all cookies
var cookies = (function() { // The getCookies() function shown earlier
var cookies = {}; // The object we will return
var all = document.cookie; // Get all cookies in one big string
if (all === "") // If the property is the empty string
return cookies; // return an empty object
var list = all.split("; "); // Split into individual name=value pairs
for(var i = 0; i < list.length; i++) { // For each cookie
var cookie = list[i];
var p = cookie.indexOf("="); // Find the first = sign
var name = cookie.substring(0,p); // Get cookie name
var value = cookie.substring(p+1); // Get cookie value
value = decodeURIComponent(value); // Decode the value
cookies[name] = value; // Store name and value
}
return cookies;
}());
// Collect the cookie names in an array
var keys = [];
for(var key in cookies) keys.push(key);
// Now define the public properties and methods of the Storage API
// The number of stored cookies
**this.length = keys.length;**
// Return the name of the nth cookie, or null if n is out of range
this.key = function(n) {
if (n < 0 || n >= keys.length) return null;
return keys[n];
};
// Return the value of the named cookie, or null.
this.getItem = function(name) { return cookies[name] || null; };
**// Store a value
this.setItem = function(key, value) {
if (!(key in cookies)) { // If no existing cookie with this name
keys.push(key); // Add key to the array of keys
this.length++; // And increment the length
}**
// Store this name/value pair in the set of cookies.
cookies[key] = value;
// Now actually set the cookie.
// First encode value and create a name=encoded-value string
var cookie = key + "=" + encodeURIComponent(value);
// Add cookie attributes to that string
if (maxage) cookie += "; max-age=" + maxage;
if (path) cookie += "; path=" + path;
// Set the cookie through the magic document.cookie property
document.cookie = cookie;
};
大家好,我在正在阅读的一本书中找到了这段代码,我看到了这行对我来说毫无意义:
**// Store a value
this.setItem = function(key, value) {
if (!(key in cookies)) { // If no existing cookie with this name
keys.push(key); // Add key to the array of keys
this.length++; // And increment the length
}**
如果我们当前在长度属性中的对象已经由前一行代码定义(this.length = keys.length;)为什么我们需要通过 this.length++ 增加它的长度?keys.push(key) 还不够吗?
编辑:
感谢所有回答的人。在盯着这段代码几分钟后,我发现第一个长度声明仅与脚本时间中的那个“阶段”相关。this.length = keys.length 表示此对象长度等于键数组的当前长度。
后来,当我们向键数组添加另一个元素时,它的长度增加了,这就是为什么我们必须通过增加它自己的值来告诉我们的对象(this.length++;)