In Javascript, is their a way to inspect an objects methods and attributes such as Python's dir()? [duplicate]
In Javascript is their a way to inspect an objects methods and attributes such as Python's dir() ?
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
Firebug had a similar function
console.dir(obj)
Or you can do one yourself
var dir = '';
for (var i in obj) dir += 'obj[' + i + '] = ' + obj[i];
alert(dir);
Yes. You can use a for..in
loop (section 12.6.4 of the spec), which loops through the enumerable properties of both the object and its prototype (if it has one), like so:
var name;
for (name in obj) {
// `name` is each of the property names, as a string; get the value
// from obj[name]
alert(name + "=" + obj[name]);
}
If you want to differentiate whether it's the object itself or its prototype that has the property, you can use obj.hasOwnProperty
:
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
// `name` is the name of a property this object has for itself
}
else {
// `name` is the name of a property the object inherits
// from its prototype
}
}
If you're using an implementation that supports some of the new ECMAScript 5 stuff, you can use Object.keys
to get an array of all of its enumerable property names, but really that's just an array version of what for..in
gives you (and for..in
is supported by every implementation of JavaScript I've ever seen or you're likely to).
When I say an "enumerable" property: Most of the built-in properties of objects defined by the specification (like length
on Array
instances, or getTime
on Date
instances) are non-enumerable and don't show up in the list. Until the 5th edition of the spec, there was no standard way to define your own non-enumerable property, but as of the latest you can do that via Object.defineProperty
/ Object.defineProperties
(sections 15.2.3.6 and 12.2.3.7 of the spec). That's not widely-supported yet.
for ( var prop in obj ) {
console.log( prop + ' is ' + obj[prop] );
}
Try using Chrome's console. If you log any sort of variable to it using console.log()
, it lets you explore all of its methods and properties, including the prototype chain. This looks sort of like this:
JavaScript has the for .. in
loop construct to help with this:
for (var name in some_object) {
// some_object[name] is the value of the property
}
However, there are some pitfalls with this approach:
- An object property can be of any type. If you need to filter the list you retrieve, you will need to use
typeof
. for .. in
will iterate over properties pulled out from the target object's prototype chain. If you want to process only properties defined on the target object itself, you should additionally test forsome_object.hasOwnProperty(name)
.
精彩评论