当前位置:首页 前端开发 正文
+1°

The commonest javascript bug

2012年08月02日 | 作者: 米豆网 - 1000seo | 分类: 前端开发 | 

Every couple of weeks somebody will come running to me: “Swizec, Swizec, I did everything right, but this javascript isn’t doing what it’s supposed to! Whatever I click only the last item works. Halp!”

Every time it’s the same bug – people just don’t understand how loops and closures play together in javascript. Invariably they loop through an array, attach the index to an event, then get frustrated when, upon triggering the event, that particular variable seems to have the wrong value.

The code usually looks something like this:

json = JSON.parse(this.responseText);
for (i = 0; i < json.links.length; i++) {
       params = json.links[i];

       row = $.ui.createRow({
                 // use params for settings, it works
                 click: function () {
                    var modalBrowser = new MiniBrowser({
                                        // it all breaks down here
                                        url: params.url,
                    });
       });
       // do some other stuff
}

Can you spot the problem?

On the first use of params everything is happy, using the local variable, which is updated on every loop iteration. But when thatclick event is triggered it still uses the local params variable … that was updated on every loop iteration.

By now, the loop has long since completed and that variable holds the last value – causing a weird-looking bug that is difficult for newbies to fix because, hey, why should I know about how pointers work? This is a scripting language damn it!

Luckily the fix is very simple:

json = JSON.parse(this.responseText);
json.links.map(function (params) {

       row = $.ui.createRow({
               // use params for settings, it works
               click: function () {
                    var modalBrowser = new MiniBrowser({
                                   // it magically still works here
                                   url: params.url,
                    });
       });
       // do some other stuff
});

Just change the for loop to a map and you don’t even have to fix anything else. Everything works as usual, except now all the code is wrapped up in a closure and caries a reference to the whole variable scope around. Simply put – when the click event is triggered all the variables that were known when it was set are still there, with exactly the same values.

Generally speaking, even a modest understanding of closures (like I have) will make itmuch easier to write javascript. Might even help you fix a memory leak or fifty.

 

From:http://swizec.com/blog/the-commonest-javascript-bug/swizec/3740

 

本文章由 米豆网 - 1000seo 于2012年08月02日发布在前端开发分类下,您可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
+复制链接 转载请注明:The commonest javascript bug-米豆网
关键字:, ,

好文章就要一起分享!

更多

目前共有1条留言

  • Santosh

    1楼
    2012 年 08 月 25 日 10:27:13 回复

    Intelligence and simplicity – easy to udnsertand how you think.

发表评论

你的大名(必填)

你的邮箱(必填)

你的网站(选填)

评论内容(必填)

😉 😐 😡 😈 🙂 😯 🙁 🙄 😛 😳 😮 mrgreen.png 😆 💡 😀 👿 😥 😎 ➡ 😕 ❓ ❗