[英]How to show all properties and methods of an object in javascript?
[英]How to find all Javascript object methods and properties?
我發現有時候我會有一個帶有一堆我似乎無法找到的方法和屬性的Object.getOwnPropertyNames
,在var和原型上都帶有Object.keys
和Object.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
功能從不顯示...有什么想法嗎?
編輯:
我在源代碼中做了一些窺探。 這是我要包裝的方法 。
然后,您可以遵循從TermBase到Eq( RDBVal , RDBOp , Eq )的繼承鏈。
r.eq().run
返回一個函數-我想包裝的函數。
@TJ 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所說 ,您不必知道在什么級別定義屬性來覆蓋它。 但是,如果你想知道的,你可以在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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.