如何查找所有Javascript对象方法和属性?

时间:2015-06-25 17:03:21

标签: javascript methods

我发现有时候我会得到一个带有一堆方法和属性的var,我似乎无法以某种方式定位,在{和} Object.keysObject.getOwnPropertyNames上的事件原型。

这是一个例子:我正在玩RethinkDB,我想覆盖run函数。但是,我不知道它在哪里 - 我需要改变什么样的对象原型等等。实际上,我找不到任何方法用上面指定的函数找到它:

> r.db('test').tableCreate('authors').run
[Function]
> r.db('test').tableCreate('authors')
{ [Function]
  args: 
   [ { [Function] args: [Object], optargs: {} },
     { [Function] data: 'authors' } ],
  optargs: {} }
> r.db('test').tableCreate('authors').prototype
{}
> r.db('test').tableCreate('authors').run
[Function]
> Object.keys(r.db('test').tableCreate('authors'))
[ 'args', 'optargs' ]
> typeof r.db('test').tableCreate('authors')
'function'
> Object.getOwnPropertyNames( r.db('test').tableCreate('authors') )
[ 'length',
  'name',
  'arguments',
  'caller',
  'prototype',
  'args',
  'optargs' ]
> Object.getOwnPropertyNames( r.db('test').tableCreate('authors').prototype )
[ 'constructor' ]

run功能永远不会出现......有什么想法吗?

编辑:

我在源代码中做了一些窥探。 this is the method I want to wrap

然后,您可以关注从TermBase到Eq(RDBValRDBOpEq)的继承链。

r.eq().run返回一个函数 - 我想要包装的函数。

@ T.J。克劳德的答案:findProps('run', r.eq())打印出一堆东西,包括:

I20150625-10:33:31.047(-7)? Props for run[[Proto]][[Proto]][[Proto]][[Proto]]
I20150625-10:33:31.047(-7)? 0: constructor
I20150625-10:33:31.047(-7)? 1: showRunWarning
I20150625-10:33:31.047(-7)? 2: run

就这样吧!

1 个答案:

答案 0 :(得分:2)

Object.keys为您提供该对象的可枚举属性名称。许多属性都不是可枚举的。

作为ssube said,您不必知道属性被定义为覆盖它的级别。但是如果您想知道,您可以在ES5及更高版本中,通过Object.getOwnPropertyNames(包括对象的非可枚举属性)和Object.getPrototypeOf,它可以让您遍历对象的原型链

示例:



function findProps(objname, obj) {
  var p;
  
  snippet.log("Props for " + objname);
  Object.getOwnPropertyNames(obj).forEach(function(name, index) {
    snippet.log(index + ": " + name);
  });
  p = Object.getPrototypeOf(obj);
  if (p != null) {
    findProps(objname + "[[Proto]]", p);
  }
}

var a = {};
Object.defineProperty(a, "foo", {      // A non-enumerable property
  value: "bar"
});

var b = Object.create(a);              // b's prototype is a
b.answer= 42;                          // An enumerable property
Object.defineProperty(a, "question", { // A non-enumerable property
  value: "Life, the Universe, and Everything"
});


var c = Object.create(b);              // c's prototype is b
c.last = "property";

findProps("c", c);

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

相关问题