簡體   English   中英

獲取任何對象的所有方法?

[英]Get all methods of any object?

在 python 中,有 dir() 函數

返回該對象的有效屬性列表

在 JS 的話我發現:

Object.getOwnPropertyNames

Object.keys

但它們沒有顯示所有屬性:

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

如何獲取所有屬性和方法的列表

concat, entries, every, find.... 

對於 Array() 例如?

您可以使用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)))

Object.getOwnPropertyNames(Array.prototype)

嘗試以您發布的方式獲取值不起作用的原因是因為您正在請求Array對象的單個實例的屬性名稱。 出於多種原因,每個實例將僅具有該實例獨有的屬性值。 由於在Array.prototype中找到的值對於特定實例不是唯一的——這是有道理的,並非所有數組都將共享相同的length值——它們為Array所有實例共享/繼承。

你可以使用Object.getOwnPropertyNames

Object.getOwnPropertyNames()方法返回直接在給定對象上找到的所有屬性(可枚舉或不可枚舉Object.getOwnPropertyNames()的數組。

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

此方法將允許您從對象的特定實例中提取所有鍵和功能(忽略不需要的):

const ROOT_PROTOTYPE = Object.getPrototypeOf({});

function getAllKeys(object) {
    // do not add the keys of the root prototype object
    if (object === ROOT_PROTOTYPE) {
        return [];
    }

    const names = Object.getOwnPropertyNames(object);

    // remove the default constructor for each prototype
    if (names[0] === 'constructor') {
        names.shift();
    }

    // iterate through all the prototypes of this object, until it gets to the root object.
    return names.concat(getAllKeys(Object.getPrototypeOf(object)));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM