Hey I’m new to JavaScript, I love the MyClass.class and MyClass.methods in Ruby, are there any equivalence in JavaScript to check out the object type and methods available?
BTW the typeof operator seems to always return 'object', I don’t know why.
The
typeofoperator does that, but it can be confusing with what it reports back.For example,
typeof nullwill tell you'object', though it is not an object (though this behaviour is defined).typeof 'a'will tell you'string', buttypeof new String('a')will tell you an'object'.The other advantage of
typeofoperator is it will not throw aReferenceErrorif its operand has not yet been declared.The methods used below to determine a function can be adapted to report the correct type (though
typeofis generally enough for primitives).You can view all the properties on an object with a
for ( in )loop.This will show all enumerable properties, including ones inherited/delegated. To disregard inherited properties, add this to the body of the loop…
To view methods (properties assigned a function), you can do this…
jsFiddle.
If not in a multi
windowenvironment (i.e. notiframes), you can simply use…jsFiddle.
…or…
jsFiddle.
If you only care about methods that implement
[[Call]](i.e. can be invoked as a function), such as theRegExpobjects in older Safaris, you can simply determine what is invokable withtypeof fn == 'function'.Since you mentioned Ruby, you could be completely crazy and implement Ruby’s
class(or close enough) andmethodsby augmentingObject.prototype, but please don’t. 🙂I also have an in-depth article on the
typeofoperator in JavaScript.