Object-oriented JavaScript
object inspection

Since the form of JavaScript objects can vary dynamically, it is especially important in this language to be able to determine just what a given object is and what members it has. This need is well provided for.

To check if an object inherits from a given class, use the instanceof operator. To determine if the object has a certain member, call typeof on the method name: this operator returns one of the following strings.

So to see if an object has a certain public method, check that the typeof operator returns "function". To check that it has a certain property, check that typeof applied to the property name returns a string reflecting the expected type, or at least not "undefined", as appropriate.

Note that there is scarcely a distinction between a public property that was never initialized, and a non-existent public property.

example: instanceof and typeof




example: for(...in...)

It is sometimes useful to look at all the members of an object. This is the use of the for(...in...) construct (the for each is equivalent to for here). It loops over all the member names in a given object:



It is also possible to determine the number of arguments present in the formal argument list of a function using its length property.

See

JavaScript 1.5 Reference:Operators: see "Special Operators"

JavaScript 1.5 Reference:Global Objects:Function