Sometimes, our code can get very complex because objects might extend the other objects. So it can get very tricky to debug the code. That’s why JS has useful feature called Reflection, which allows us to see what is inside the object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var person = { firstname: 'Default', lastname: 'Default', getFullName: function() { return this.firstname + ' ' + this.lastname; } } var john = { firstname: 'John', lastname: 'Doe' } // don't do this EVER! for demo purposes only!!! john.__proto__ = person; |
The above code will sorta extend the john object with user object. If you run the code below
1 2 3 |
for (var prop in john) { console.log(prop + ': ' + john[prop]); } |
Output:
1 2 3 4 5 |
firstname: John lastname: Doe getFullName: function () { return this.firstname + ' ' + this.lastname; } |
Below code, shows only the content of the john object
1 2 3 4 5 |
for (var prop in john) { if (john.hasOwnProperty(prop)) { console.log(prop + ': ' + john[prop]); } } |
Output:
1 2 |
firstname: John lastname: Doe |