Skip to content

Instantly share code, notes, and snippets.

@fijiwebdesign
Last active June 29, 2016 00:05
Show Gist options
  • Save fijiwebdesign/dab41ba5878b4cdfed4c687606a96085 to your computer and use it in GitHub Desktop.
Save fijiwebdesign/dab41ba5878b4cdfed4c687606a96085 to your computer and use it in GitHub Desktop.
Object keys iteration with forEach
// iteration using for..in loop and hasOwnProperty
var Person = {
name: 'mr smith',
profession: 'dandy fella',
age: 10000,
reset: function() {
for (var prop in this) {
if (prop == 'reset' || !this.hasOwnProperty(prop)) {
console.log("leave it alone", prop)
} else {
this[prop] = null
}
}
}
}
// Iteration using forEach
var Person = {
name: 'mr smith',
profession: 'dandy fella',
age: 10000,
reset: function() {
Object.keys(this).forEach(function(prop) {
if (prop != 'reset') {
this[prop] = null; // this now references Person
}
}, this) // this references Person
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment