Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Created September 21, 2010 16:44
Show Gist options
  • Save elijahmanor/590010 to your computer and use it in GitHub Desktop.
Save elijahmanor/590010 to your computer and use it in GitHub Desktop.
Check hasOwnProperty in for...in
// Check hasOwnProperty in for...in
// When you are using the for...in loop in JavaScript
// you must be careful to also check the object
// you are enumerating to see if it contains
// the property before proceeding. The reason for
// this is that the for...in loop also iterates
// over the prototype's properties as well */
var Person = function( firstName, lastName ) {
this.firstName = firstName;
this.lastName = lastName;
return this;
};
Person.prototype = {
isMarried : false,
hasKids: false
};
var john = new Person( "John", "Smith" ),
linda = new Person( "Linda", "Davis" );
john.isMarried = true;
console.log( "Not Checking hasOwnProperty" );
for ( name in john ) {
console.log( name + ": " + john[name] );
//Outputs
// firstName: John
// lastName: Smith
// isMarried: true
// hasKids: false
}
console.log( "Checking hasOwnProperty" );
for ( name in linda ) {
if ( linda.hasOwnProperty(name) ) {
console.log( name + ": " + linda[name] ); //Outputs: firstName, lastName
//Outputs
// firstName: Linda
// lastName: Davis
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment