Created
February 5, 2013 21:09
-
-
Save sudowork/4717678 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var prop, x; | |
var animal = { | |
type: 'Missing No.', | |
say: function (phrase) { | |
return this.type + ' says hello.'; | |
} | |
}; | |
var dog = Object.create(animal); | |
dog.type = 'Dog'; | |
dog.bark = function () { | |
return 'WOOF! ' + this.say() + ' WOOF!'; | |
} | |
var poodle = Object.create(dog); | |
poodle.bark = function () { | |
return 'bark. ' + this.say() + ' bark.'; | |
} | |
// log the properties in animal first | |
for (prop in animal) { | |
console.log(prop); // > say, type | |
} | |
// now log the properties that for...in sees in poodle | |
for (prop in poodle) { | |
console.log(prop); // > bark, say, type | |
// but we only defined bark directly on poodle | |
} | |
// if we only want the properties directly on poodle, we can use Object.hasOwnProperty | |
for (prop in poodle) { | |
if (poodle.hasOwnProperty(prop)) { | |
console.log(prop); // > bark | |
} | |
} | |
// We can use for...in on arrays as well, but it probably doesn't do what you'd expect (also, it doesn't guarantee order) | |
var someArray = ['a', 'b', 'c']; | |
for (x in someArray) { | |
console.log(x); // > 0, 1, 2 | |
} | |
// you could use this (order is not guaranteed) | |
for (x in someArray) { | |
console.log(someArray[x]); // 'a', 'b', 'c' | |
} | |
// but.... you really should be using this | |
someArray.forEach(function (y) { | |
console.log(y); // 'a', 'b', 'c' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment