Skip to content

Instantly share code, notes, and snippets.

@xer0x
Created October 26, 2011 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xer0x/1315438 to your computer and use it in GitHub Desktop.
Save xer0x/1315438 to your computer and use it in GitHub Desktop.
olark javascript
// Original snippet
function inspectObject(object) {
for (key in object) {
console.log("the attribute " + key + " is equal to " + object[key]);
}
}
var widget = new Widget();
inspectObject(widget);
// Possible problems
1. key is overwritten if already defined.
To fix this change the loop to: for (var key in object)
However, since JS is function scoped the key will be scoped for the whole inspectObject().
Crockford says rather than write concise code that we should write what JS actually is doing, and so I'll put 'var key' on its own line.
var key;
for (key in object) {
2. for-in will iterate over properties further up the prototype chain.
To fix this add test for object.hasOwnProperty(key), if you only want the object's properties.
function inspectObject(object) {
for (key in object) {
if (object.hasOwnProperty(key)) {
console.log("the attribute " + key + " is equal to " + object[key]);
}
}
}
3. inspectObject() might be overwritten if already defined.
To fix this add an anonymous function wrapper inside the script block.
The final script might look like:
(function () {
function inspectObject(object) {
var key;
for (key in object) {
if (object.hasOwnProperty(key)) {
console.log("the attribute " + key + " is equal to " + object[key]);
}
}
}
var widget = new Widget();
inspectObject(widget);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment