Java Reference
In-Depth Information
As mentioned earlier, objects can inherit properties from other objects, so all objects have
a method called hasOwnProperty() . This can be used to check whether an object has
a property that is its own, rather than one that has been inherited from another object:
superman.hasOwnProperty('city');
<< false
superman.hasOwnProperty('name');
<< true
Finding all the Properties of an Object
We can loop through all of an object's properties and methods by using a for in loop.
For example, to log all the properties of the superman object to the console, we could
use:
for(var key in superman) {
console.log(key + ": " + superman[key]);
}
<< "name: Superman"
<< "real name: Clark Kent"
<< "height: 75"
<< "weight: 235"
<< "hero: true"
<< "villain: false"
<< "allies: Batman,Supergirl,Superboy"
<< "fly: function (){
console.log(\"Up, up and away!\");
}"
In this example, we create a variable called key . This is then used to represent the name of
each property or method in the superman object inside the for loop.
To make sure that only an object's own properties are returned, a quick check can be im-
plemented beforehand:
Search WWH ::




Custom Search