JavaScript内省是完整的

初学JavaScript的问题。 我有点宠爱Python的dir内置函数。 我想要发现node.js REPL中任何对象的属性/方法。 我已经看到了这个问题 。 在一个空数组[]的简单情况下,接受的答案失败(在node REPL中)。 例如:

 for(var prop in []){console.log(prop);} # returns undefined, prints nothing [].length # returns 0 

由于for循环没有发现数组的length方法,我不认为这是正确的自省。 那么,有人可以在这里填空:

 function magic(some_object) { # magic goes here } console.log(magic([])) # should print a list that includes 'length' 

或者,这是不可能的,或者只有“用户types”可能?

浏览器兼容性需要多久? 所有的现代浏览器都应该支持Object.getOwnPropertyNames() 。 使用你的例子, Object.getOwnPropertyNames([])将返回["length"]

更多信息在这里: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

编辑:其他例子:

  • Object.getOwnPropertyNames([1, 2, 3]); 返回["0", "1", "2", "length"]

  • Object.getOwnPropertyNames(String); 返回["prototype", "quote", "substring", "toLowerCase", "toUpperCase", "charAt", "charCodeAt", "contains", "indexOf", "lastIndexOf", "startsWith", "endsWith", "trim", "trimLeft", "trimRight", "toLocaleLowerCase", "toLocaleUpperCase", "localeCompare", "match", "search", "replace", "split", "substr", "concat", "slice", "fromCharCode", "length", "name", "arguments", "caller"]

编辑#2:好吧,看到你正在寻找完整的属性和方法列表,包括inheritance的属性和方法,我借用了另外两个SO问题(下面链接),并提出一个解决scheme,让你更接近:

 var findProperties = function(obj) { var aPropertiesAndMethods = []; do { aPropertiesAndMethods = aPropertiesAndMethods.concat(Object.getOwnPropertyNames(obj)); } while (obj = Object.getPrototypeOf(obj)); for ( var a = 0; a < aPropertiesAndMethods.length; ++a) { for ( var b = a + 1; b < aPropertiesAndMethods.length; ++b) { if (aPropertiesAndMethods[a] === aPropertiesAndMethods[b]) { aPropertiesAndMethods.splice(a--, 1); } } } return aPropertiesAndMethods; } 

所以如果你使用调用findProperties([]) ,它会返回["length", "join", "reverse", "sort", "push", "pop", "shift", "unshift", "splice", "concat", "slice", "lastIndexOf", "indexOf", "forEach", "map", "reduce", "reduceRight", "filter", "some", "every", "iterator", "constructor", "toSource", "toString", "toLocaleString", "valueOf", "watch", "unwatch", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]

链接的问题

JavaScriptinheritance,reflection和原型链走?

如何合并Javascript中的两个数组和重复删除项目

Interesting Posts