在 Javascript 中,它们是一种检查对象方法和属性的方法,例如 Python 的 dir() 吗?
在 Javascript 中,他们是一种检查对象方法和属性的方法,例如 Python 的 dir() ?
dir(object) returns
object.height
object.width
object.compute_days_till_birthday()
etc.....
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.....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Firebug有类似的功能
或者你可以自己做一个
Firebug had a similar function
Or you can do one yourself
是的。您可以使用
for..in
循环(规范),它循环遍历对象及其原型(如果有的话)的可枚举属性,如下所示:如果您想区分是对象本身还是其原型有属性,您可以使用
obj.hasOwnProperty
:如果您使用的实现支持某些新的 ECMAScript 5 的东西,您可以使用
Object.keys
来获取其所有可枚举属性名称的数组,但实际上这只是for..in 的数组版本
为您提供(并且我见过的或您可能看到的每个 JavaScript 实现都支持for..in
)。当我说“可枚举”属性时:规范定义的对象的大多数内置属性(例如
Array
实例上的length
或getTime
Date
实例上的 code> )是不可枚举并且不会显示在列表中。在规范的第 5 版之前,还没有定义您自己的不可枚举属性的标准方法,但截至最新,您可以通过 Object.defineProperty 来实现这一点 /Object.defineProperties
(规范第 15.2.3.6 和 12.2.3.7 节)。这还没有得到广泛支持。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:If you want to differentiate whether it's the object itself or its prototype that has the property, you can use
obj.hasOwnProperty
: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 whatfor..in
gives you (andfor..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
onArray
instances, orgetTime
onDate
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 viaObject.defineProperty
/Object.defineProperties
(sections 15.2.3.6 and 12.2.3.7 of the spec). That's not widely-supported yet.尝试使用 Chrome 的控制台。如果您使用console.log() 向其记录任何类型的变量,它可以让您探索其所有方法和属性,包括原型链。这看起来有点像这样:
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 具有
for .. in
循环构造来帮助解决此问题:但是,这种方法存在一些缺陷:
typeof
。for .. in
将迭代从目标对象的原型链中提取的属性。如果您只想处理目标对象本身定义的属性,则应另外测试some_object.hasOwnProperty(name)
。JavaScript has the
for .. in
loop construct to help with this:However, there are some pitfalls with this approach:
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)
.