Monday, March 14, 2011

Javascript Quiz: Question 1


Question: What is the output?
var o = {
  a: 1,
  b: 2,
  c: 3
};
for (var x in o) {
  setTimeout(function() {
    console.log(x);
  }, 1000 * Math.random());
}







The Dojo Toolkit has a d.forEach method which eliminates closure issues like this, but is designed to work on array or NodeList objects. I am not aware of any dojo methods for iterating over object properties.


function forEach(o, context, f) {
  var x;
  if (!f) {
    f = context;
    context = this;
  }
  for (x in o) {
    if (o.hasOwnProperty(x)) {
      f.call(context, x, o[x], o);
    }
  }
}




References
http://stackoverflow.com/questions/1963102/what-does-the-jslint-error-body-of-a-for-in-should-be-wrapped-in-an-if-statement
http://www.jslint.com/
http://www.google.com/search?q=js+closures

No comments:

Post a Comment