一尘不染

ES6遍历类方法

javascript

考虑到这一节课;我将如何迭代其中包含的方法?

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

let cat = window.cat = new Animal('cat')

我尝试过的以下操作均未成功:

for (var each in Object.getPrototypeOf(cat) ){
    console.log(each);
}

阅读 414

收藏
2020-05-01

共1个答案

一尘不染

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

Object.getOwnPropertyNames( Animal.prototype )
// [ 'constructor', 'getAnimalType' ]
2020-05-01