我发现有时我会有一个带有一堆方法和属性的 var,但我似乎无法以某种方式找到这些方法和属性,例如带有 Object.keys
和 Object.event 的事件。 var 和原型(prototype)上的 getOwnPropertyNames
。
这是一个示例:我正在使用 RethinkDB,我想重写 run
函数。但是,我不知道它位于哪里——我需要更改什么对象原型(prototype)等等。事实上,我找不到任何使用上面指定的函数来查找它的方法:
> 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 的继承链( RDBVal 、 RDBOp 、 Eq )。
r.eq().run
返回一个函数——我想要包装的函数。
@T.J. Crowder 的回答: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
就是这样!
最佳答案
Object.keys
为您提供该对象的可枚举属性名称。许多属性是不可枚举的。
如ssube said ,您不必知道属性是在什么级别定义的来覆盖它。但如果你想知道,你可以在 ES5 及更高版本中通过 Object.getOwnPropertyNames
,其中包括对象的不可枚举属性,以及 Object.getPrototypeOf
,它允许您遍历对象的原型(prototype)链。
示例:
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>
关于javascript - 如何查找所有Javascript对象的方法和属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056484/