ES6迭代类方法

sea*_*ick 34 javascript ecmascript-6

鉴于此课程; 我将如何迭代它包含的方法?

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

let cat = window.cat = new Animal('cat')
Run Code Online (Sandbox Code Playgroud)

我试过的是以下但没有成功:

for (var each in Object.getPrototypeOf(cat) ){
    console.log(each);
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 56

您可以在原型上使用Object.getOwnPropertyNames:

Object.getOwnPropertyNames( Animal.prototype )
// [ 'constructor', 'getAnimalType' ]
Run Code Online (Sandbox Code Playgroud)

  • @seasick它可以工作,但你也需要使用`Object.getPrototypeOf`来获得原型:`Object.getOwnPropertyNames(Object.getPrototypeOf(cat))` (5认同)
  • @seasick哦,如果你想要`Animal`继承自其他基类的方法,你还必须递归地将原型链向上走到链中的每个对象`getOwnPropertyNames`.我不认为有另一种方法可以获得不可枚举的属性 (2认同)

goo*_*gic 13

我知道,我知道,但嘿......

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" ]
Run Code Online (Sandbox Code Playgroud)

  • x [name]将执行一个getter.使用(Object.getOwnPropertyDescriptor(x,name)|| {})来防止这种情况.获取|| typeof x [name] == ... (2认同)

Bas*_*sav 7

如果您只需要函数(例如替换为_.functions) ,请尝试这种一种线性方式

function getInstanceMethodNames (obj) {
    return Object
        .getOwnPropertyNames (Object.getPrototypeOf (obj))
        .filter(name => (name !== 'constructor' && typeof obj[name] === 'function'));
}
Run Code Online (Sandbox Code Playgroud)


Leo*_*tra 7

这有点复杂,但从整个原型链中获取方法。

function getAllMethodNames (obj, depth = Infinity) {
    const methods = new Set()
    while (depth-- && obj) {
        for (const key of Reflect.ownKeys(obj)) {
            methods.add(key)
        }
        obj = Reflect.getPrototypeOf(obj)
    }
    return [...methods]
}
Run Code Online (Sandbox Code Playgroud)


Pav*_* Ye 6

由于 ES6 类上的方法是不可枚举的,因此您别无选择,只能使用Object.getOwnPropertyNames()来获取其所有属性的数组。

实现此目标后,有多种方法可以提取方法,其中最简单的可能是使用Array.prototype.forEach()

查看以下代码片段:

Object.getOwnPropertyNames(Animal.prototype).forEach((value) => {
    console.log(value);
})
Run Code Online (Sandbox Code Playgroud)