2017-03-07 16 views
0

在蟒蛇字有目錄()函數獲取任何對象的所有方法?

返回該對象

在JS的話,我發現有效屬性的列表:

Object.getOwnPropertyNames 

Object.keys 

,但他們不」 t顯示全部屬性:

> Object.getOwnPropertyNames([]) 
[ 'length' ] 

H以獲得所有屬性和方法列表

concat, entries, every, find.... 

對於Array()例如?

+2

[有沒有方法可以在JavaScript中打印對象的所有方法?](http://stackoverflow.com/questions/152483/is-there-a-way-to-print-all-methods -of-an-object-in-javascript) –

+0

@ ErikBrodyDreyer - 這個問題並不是重複的,因爲在2008年沒有方法獲得非枚舉屬性名稱。 – RobG

回答

1

Object.getOwnPropertyNames(Array.prototype)

爲什麼試圖獲取值,你貼不工作的方式,是因爲您所請求的屬性名稱單個實例Array對象。由於多種原因,每個實例只有屬性值爲唯一的。由於在Array.prototype中找到的值不是唯一的特定實例 - 這是有道理的,並非所有陣列將共享length相同的值 - 它們是Array的所有實例的共享/繼承。

1

您可以使用Object.getOwnPropertyNamesObject.getPrototypeOf來遍歷原型鏈並收集每個對象的所有屬性。

var result = [] 
 
var obj = [] 
 
do { 
 
    result.push(...Object.getOwnPropertyNames(obj)) 
 
} while ((obj = Object.getPrototypeOf(obj))) 
 

 
document.querySelector("pre").textContent = result.join("\n")
<pre></pre>

這不論他們是否會繼承或枚舉處理所有屬性。但這不包括Symbol屬性。要包括這些,你可以使用Object.getOwnPropertySymbols

var result = [] 
var obj = [] 
do { 
    result.push(...Object.getOwnPropertyNames(obj), ...Object.getOwnPropertySymbols(obj)) 
} while ((obj = Object.getPrototypeOf(obj))) 
+0

由於OP需要方法,因此應該爲Function對象(或至少可調用的對象)設置一個過濾器。 – RobG

+0

@RobG:也許吧。 OP提到*「屬性和方法」*,所以我不確定應該包含多少或多少。 – 2017-03-07 21:05:46

+0

是的,這個問題有點不清楚。 – RobG

0

你可以使用Object.getOwnPropertyNames

Object.getOwnPropertyNames()方法返回直接發現在給定對象的所有屬性(枚舉與否)的陣列。

console.log(Object.getOwnPropertyNames(Array.prototype));
.as-console-wrapper { max-height: 100% !important; top: 0; }