Create a dictionary object (dictionary) instance in JavaScript and a typical javascript instance
For JavaScript, its own Array object is only an Array and cannot be used to obtain the stored data through keywords. jQuery source code provides a very good way to solve this problem, first look at the source code:
Copy codeThe Code is as follows:
Function createCache (){
Var keys = [];
Function cache (key, value ){
// Use (key + "") to avoid collision with native prototype
// Properties (see Issue #157)
If (keys. push (key + = "")> Expr. cacheLength ){
// Only keep the most recent entries
Delete cache [keys. shift ()];
}
Return (cache [key] = value );
}
Return cache;
}
The above Source Code creates a cache for the compilation result. The Code call method is as follows:
Copy codeThe Code is as follows:
Var codecache = createCache ();
In the source code, keys is used to save the key, and the cache object is used to save the key-value pair, and the global variable Expr is used. the maximum number of cacheLength control keys. If the maximum number is exceeded, the first key and key-value pair are automatically deleted.
This Code uses the closure structure to prevent external code from accessing the keys variable. This ensures the security of the keys variable. Of course, due to the characteristics of JavaScript statements, external code can still modify the cache attribute to make the key-value pair do not match. However, as long as you do not intentionally spoof it, it should not be too relevant.
Of course, it cannot swear a perfect dictionary object, because it does not provide key functions such as primary key duplicate judgment. Interested friends can perfect it.