C.js代码:

文章插图

文章插图
/** * 有BUG */(function (global) {var _id;var _map;var _length;global.C = function () {_map = {};_length = 0;};global.C.prototype = {setId: function (id) {_id = id;},getId: function () {return _id;},put: function (key, value) {if (!_map.hasOwnProperty(key)) {_length++;}_map[key] = value;},get: function (key) {if (_map.hasOwnProperty(key)) {return _map[key];}return null;},};global.C.prototype.constructor = global.C;})(window);View Code错误原因:代码中_id、_map、_length变量是C的所有实例共用的 。
D.js代码:

文章插图

文章插图
【JS 闭包 BUG】/** * 无BUG */(function (global) {global.D = function () {this._map = {};this._length = 0;};global.D.prototype = {setId: function (id) {this._id = id;},getId: function () {return this._id;},put: function (key, value) {if (!this._map.hasOwnProperty(key)) {this._length++;}this._map[key] = value;},get: function (key) {if (this._map.hasOwnProperty(key)) {return this._map[key];}return null;},};global.D.prototype.constructor = global.D;})(window);View Codetest.html代码:

文章插图

文章插图
<!DOCTYPE html><html><head><title>JS闭包测试</title><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><style type="text/css"></style><script type="text/javascript" src="https://tazarkount.com/read/jquery-1.7.1.js"></script><script type="text/javascript" src="https://tazarkount.com/read/C.js"></script><script type="text/javascript" src="https://tazarkount.com/read/D.js"></script></head><body><input type="button" value="https://tazarkount.com/read/测试1" onclick="test()" /><div id="div" style="height:800px;"></div><script type="text/javascript">var div = $("#div");function log(msg) {div.append(msg + " ");}function logLine(msg) {div.append(msg + "<br />");}//测试function test() {var c1 = new C();var c2 = new C();var d1 = new D();var d2 = new D();c1.setId("id1");c2.setId("id2");d1.setId("id1");d2.setId("id2");logLine(c1.getId());logLine(c2.getId());logLine(d1.getId());logLine(d2.getId());debugger;c1.put("key1", "value1");c2.put("key1", "value2");d1.put("key1", "value1");d2.put("key1", "value2");logLine(c1.get("key1"));logLine(c2.get("key1"));logLine(d1.get("key1"));logLine(d2.get("key1"));}</script></body></html>View Code测试截图:

文章插图
- 春季老年人吃什么养肝?土豆、米饭换着吃
- 三八妇女节节日祝福分享 三八妇女节节日语录
- 老人谨慎!选好你的“第三只脚”
- 校方进行了深刻的反思 青岛一大学生坠亡校方整改校规
- 脸皮厚的人长寿!有这特征的老人最长寿
- 长寿秘诀:记住这10大妙招 100%增寿
- 春季老年人心血管病高发 3条保命要诀
- 眼睛花不花要看四十八 老年人怎样延缓老花眼
- 香槟然能防治老年痴呆症? 一天三杯它人到90不痴呆
- 老人手抖的原因 为什么老人手会抖
