在蟒蛇字有目錄()函數獲取任何對象的所有方法?
返回該對象
在JS的話,我發現有效屬性的列表:
Object.getOwnPropertyNames
Object.keys
,但他們不」 t顯示全部屬性:
> Object.getOwnPropertyNames([])
[ 'length' ]
H以獲得所有屬性和方法列表
concat, entries, every, find....
對於Array()例如?
在蟒蛇字有目錄()函數獲取任何對象的所有方法?
返回該對象
在JS的話,我發現有效屬性的列表:
Object.getOwnPropertyNames
Object.keys
,但他們不」 t顯示全部屬性:
> Object.getOwnPropertyNames([])
[ 'length' ]
H以獲得所有屬性和方法列表
concat, entries, every, find....
對於Array()例如?
Object.getOwnPropertyNames(Array.prototype)
爲什麼試圖獲取值,你貼不工作的方式,是因爲您所請求的屬性名稱單個實例的Array
對象。由於多種原因,每個實例只有屬性值爲唯一的。由於在Array.prototype
中找到的值不是唯一的特定實例 - 這是有道理的,並非所有陣列將共享length
相同的值 - 它們是Array
的所有實例的共享/繼承。
您可以使用Object.getOwnPropertyNames
和Object.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)))
你可以使用Object.getOwnPropertyNames
的
Object.getOwnPropertyNames()
方法返回直接發現在給定對象的所有屬性(枚舉與否)的陣列。
console.log(Object.getOwnPropertyNames(Array.prototype));
.as-console-wrapper { max-height: 100% !important; top: 0; }
[有沒有方法可以在JavaScript中打印對象的所有方法?](http://stackoverflow.com/questions/152483/is-there-a-way-to-print-all-methods -of-an-object-in-javascript) –
@ ErikBrodyDreyer - 這個問題並不是重複的,因爲在2008年沒有方法獲得非枚舉屬性名稱。 – RobG