【问题标题】:Unable to Iterate through the function's properties and methods in Javascript无法在 Javascript 中遍历函数的属性和方法
【发布时间】:2015-04-17 16:52:12
【问题描述】:
我想知道是否可以遍历 Object 函数(或类似的内置函数)的方法和属性
我可以通过for(var key in window) console.log(key)遍历文档和窗口对象
但是,作为函数的“对象”不是这样工作的。正如我在MDN 看到的,有很多方法可以实现,例如 - Object.isExtensible() 但是,for(var key in Object) console.log(key) 只会返回 undefined
感谢您的帮助。
【问题讨论】:
标签:
javascript
loops
object
properties
iteration
【解决方案1】:
使用Object.getOwnPropertyNames:
// functions directly within Object
Object.getOwnPropertyNames(Object).forEach(function(name) {
// do whatever you want with the name here
}
// methods of Object instances
Object.getOwnPropertyNames(Object.prototype).forEach(function(name) {
// do whatever you want with the name here
}