Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Iterate over class methods

Given this class; how would i iterate over the methods that it includes?

class Animal {     constructor(type){         this.animalType = type;     }     getAnimalType(){         console.log('this.animalType: ', this.animalType );     } }  let cat = window.cat = new Animal('cat') 

What I have tried is the following with no success:

for (var each in Object.getPrototypeOf(cat) ){     console.log(each); } 
like image 523
seasick Avatar asked Jun 17 '15 03:06

seasick


2 Answers

You can use Object.getOwnPropertyNames on the prototype:

Object.getOwnPropertyNames( Animal.prototype ) // [ 'constructor', 'getAnimalType' ] 
like image 138
Paul Avatar answered Sep 22 '22 07:09

Paul


i know, i know, but hey...

const isGetter = ( x, name ) => ( Object.getOwnPropertyDescriptor( x, name ) || {} ).get  const isFunction = ( x, name ) => typeof x[ name ] === "function";  const deepFunctions = x =>     x && x !== Object.prototype &&     Object.getOwnPropertyNames( x )      .filter( name => isGetter( x, name ) || isFunction( x, name ) )      .concat( deepFunctions( Object.getPrototypeOf( x ) ) || [] );  const distinctDeepFunctions = x => Array.from( new Set( deepFunctions( x ) ) );  const userFunctions = x => distinctDeepFunctions( x ).filter( name => name !== "constructor" && !~name.indexOf( "__" ) );      // example usage    class YourObject {        hello() { return "uk"; }     goodbye() { return "eu"; }  }    class MyObject extends YourObject {     hello() { return "ie"; }     get when() { return "soon"; }   }    const obj = new MyObject();  console.log( userFunctions( obj ) ); // [ "hello", "when", "goodbye" ]
like image 24
goofballLogic Avatar answered Sep 19 '22 07:09

goofballLogic