Created
March 21, 2018 14:21
-
-
Save wicharek/01abfd68b99e8206229b90dd0bc917cf to your computer and use it in GitHub Desktop.
JavaScript: get all method names of the provided object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getAllClassMethods = (obj) => { | |
let keys = [] | |
let topObject = obj | |
const onlyOriginalMethods = (p, i, arr) => | |
typeof topObject[p] === 'function' && // only the methods | |
p !== 'constructor' && // not the constructor | |
(i === 0 || p !== arr[i - 1]) && // not overriding in this prototype | |
keys.indexOf(p) === -1 // not overridden in a child | |
do { | |
const l = Object.getOwnPropertyNames(obj) | |
.sort() | |
.filter(onlyOriginalMethods) | |
keys = keys.concat(l) | |
// walk-up the prototype chain | |
obj = Object.getPrototypeOf(obj) | |
} while ( | |
// not the the Object prototype methods (hasOwnProperty, etc...) | |
obj && Object.getPrototypeOf(obj) | |
) | |
return keys | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment