beyond applications and software

JavaScript summed up #8: Reflection

Inspecting objects at runtime is what’s called “reflection”. Maybe you want to know – at runtime – what methods an object has or what type of object it is. You’ve got a couple of tools at hand to do this in JavaScript:

typeof & constructor

Before you read on, you should be familiar with both the “typeof” keyword and the “constructor” property. If you’re not (yet) familiar, you can get yourself up to speed by reading my previous post about type checking.

for…in

With for…in you can iterate over the properties of an object. So if you want to know which methods an object has, you can write something like this:

for ( prop in myObject ){
    if (typeof myObject[prop] == 'function') {
        // ...that's a function
    }
}

hasOwnProperty

Iterating through an object’s property is fine – unless you need to know if it’s exactly _this_ object, and not one of its parents in the inheritance hiearchy, that has this property.
To find out just that, you can use “hasOwnProperty” which doesn’t look up in the prototype-chain, but only in the very object you’re calling the method upon:

// true, if a property named "myMethod" exists in the object itself
myObject.hasOwnProperty('myMethod');
Share this:
  • Print
  • email
  • PDF
  • Twitter
  • Digg
  • del.icio.us
  • MisterWong
  • StumbleUpon
  • Facebook
  • Netvibes
  • Google Bookmarks
  • FriendFeed
  • Mixx
  • Live
  • Ping.fm
  • Technorati
  • Yigg

2 comments

1 Phil Idem { 09.24.09 at 7:27 pm }

A better alternative to using typeof is to use the built-in “constructor” property. For example:
for ( prop in myObject ){
var property = myObject[prop];
if (property && property.constructor === Function) {
// …that’s a function
}
}

The “constructor” argument references the function that created the object.

function MyConstructor()
{
}

var obj = new MyConstructor();
alert(obj.constructor === MyConstructor); // true

Might be worth mentioning that you can check for property existence with one of these expressions:
myObject.myProperty !== undefined
myObject.myProperty === undefined

Don’t use this: typeof(myObject.myProperty) != “undefined”

2 Tobias Günther { 09.25.09 at 9:08 am }

Hi Phil, related to that, you can look at my previous article on “Type Checking” (http://blog.puremedia-online.de/2009/08/20/javascript-summed-up-3-type-checking/) where ‘constructor’ is explained.

Leave a Comment