獲取 JavaScript 中任何物件的全部方法
我們需要編寫一個程式(函式)接收一個物件引用並返回駐留在該物件上的所有方法(成員函式)的陣列。我們只需要在陣列中返回方法,而不返回可能具有除函式型別外的其他型別值的任何其他屬性。
我們將使用 Object.getOwnPropertyNames 函式
Object.getOwnPropertyNames() 方法返回在給定物件上直接找到的所有屬性(可列舉或不可列舉)的陣列。然後我們將過濾該陣列以僅包含資料型別為“函式”的屬性。
示例
const returnMethods = (obj = {}) => { const members = Object.getOwnPropertyNames(obj); const methods = members.filter(el => { return typeof obj[el] === 'function'; }) return methods; }; console.log(returnMethods(Array.prototype));
輸出
控制檯中的輸出將是 -
[ 'constructor', 'concat', 'copyWithin', 'fill', 'find', 'findIndex', 'lastIndexOf', 'pop', 'push', 'reverse', 'shift', 'unshift', 'slice', 'sort', 'splice', 'includes', 'indexOf', 'join', 'keys', 'entries', 'values', 'forEach', 'filter', 'flat', 'flatMap', 'map', 'every', 'some', 'reduce', 'reduceRight', 'toLocaleString', 'toString' ]
廣告