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)
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)
如果您只需要函数(例如替换为_.functions) ,请尝试这种一种线性方式
function getInstanceMethodNames (obj) {
return Object
.getOwnPropertyNames (Object.getPrototypeOf (obj))
.filter(name => (name !== 'constructor' && typeof obj[name] === 'function'));
}
Run Code Online (Sandbox Code Playgroud)
这有点复杂,但从整个原型链中获取方法。
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)
由于 ES6 类上的方法是不可枚举的,因此您别无选择,只能使用Object.getOwnPropertyNames()来获取其所有属性的数组。
实现此目标后,有多种方法可以提取方法,其中最简单的可能是使用Array.prototype.forEach()。
查看以下代码片段:
Object.getOwnPropertyNames(Animal.prototype).forEach((value) => {
console.log(value);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10786 次 |
| 最近记录: |