如何在Javascript对象中找到隐藏的属性/方法? [英] How to find hidden properties/methods in Javascript objects?

查看:517
本文介绍了如何在Javascript对象中找到隐藏的属性/方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动确定所有属性(包括 通过将其概括为给定的Javascript对象中的隐藏对象) 功能:

I would like to automatically determine all of the properties (including the hidden ones) in a given Javascript object, via a generalization of this function:

function keys(obj) {
    var ll = [];
    for(var pp in obj) {
        ll.push(pp);
    }
    return ll;
}

这适用于用户定义的对象,但对于许多内置函数却无效:

This works for user defined objects but fails for many builtins:

repl> keys({"a":10,"b":2});  // ["a","b"]
repl> keys(Math) // returns nothing!

基本上,我想编写Python的dir()和help()的等效项,它们在探索新对象时确实非常有用.

Basically, I'd like to write equivalents of Python's dir() and help(), which are really useful in exploring new objects.

我的理解是,只有内置对象才具有隐藏属性(用户代码此处)一样.但是有更好的方法吗?

My understanding is that only the builtin objects have hidden properties (user code evidently can't set the "enumerable" property till HTML5), so one possibility is to simply hardcode the properties of Math, String, etc. into a dir() equivalent (using the lists such as those here). But is there a better way?

编辑:好的,到目前为止,我看到的最好的答案是在

Ok, the best answer I've seen so far is on this thread. You can't easily do this with your own JS code, but the next best thing is to use console.dir in Chrome's Developer Tools (Chrome -> View -> Developer -> Developer Tools). Run console.dir(Math) and click the triangular drill down to list all methods. That's good enough for most interactive/discovery work (you don't really need to do this at runtime).

推荐答案

ECMAScript第5版.定义Object.getOwnPropertyNames,它返回传入对象的所有属性的数组,包括不可枚举的属性.到目前为止,只有Chrome浏览器实现了此功能.

ECMAScript 5th ed. defines Object.getOwnPropertyNames that returns an array of all properties of the passed in object, including the ones that are non-enumerable. Only Chrome has implemented this so far.

Object.getOwnPropertyNames({a: 10, b: 2});

给予["b", "a"](无特定顺序)

Object.getOwnPropertyNames(Math);

给予["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "LN2", "cos", "pow", "log", "tan", "sqrt", "ceil", "asin", "abs", "max", "exp", "atan2", "random", "round", "floor", "acos", "atan", "min", "sin"]

这篇关于如何在Javascript对象中找到隐藏的属性/方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆