LoginSignup
5
4

More than 5 years have passed since last update.

JavaScript Classのpropertyとmethodを列挙する

Posted at

色々参考にしてclassのメソッドとプロパティを列挙する方法を調べてみました。
作ってみたけど結局使わないような。
まだまだ不備があるかもしれません。

javascript
class First {
  constructor() {
    this.dataFirst = "first";
  }
  funcFirst() {
    console.log("funcFirst");
  }
  static staticFuncFirst() {
    console.log("static funcFirst")
  }
}

class Second extends First {
  constructor() {
    super();
    this.dataSecond = "second";
  }
  funcSecond() {
    console.log("funcSecond");
  }
  static staticFuncSecond() {
    console.log("static funcSecond")
  }
}

class Third extends Second {
  constructor() {
    super();
    this.dataThird = "third";
  }
  funcThird() {
    console.log("funcThird");
  }
  static staticFuncThird() {
    console.log("static funcThird")
  }
}

function getAllMethodNames(object) {
  let methods = new Set();

  //Objectオブジェクトにまでたどるとobj.__proto__はnull。もしくはOwnPropertyNamesに__proto__が出てくる
  for(let obj = Object.getPrototypeOf(object); obj !== null && obj.__proto__ !== null; obj = Object.getPrototypeOf(obj)) {
    let names = Object.getOwnPropertyNames(obj)
    names.forEach((x) => methods.add(x));
  }
  return methods;
}

function getAllStaticMethodNames(className) {
  let methods = new Set();

  //typeof __proto__ が"function"の間はユーザが定義したclass。"object"になるとObjectオブジェクト
  for(let obj = className; obj !== null && typeof obj.__proto__ === "function"; obj = Object.getPrototypeOf(obj)) {
    let names = Object.getOwnPropertyNames(obj)
    names = names.filter((prop) => { return typeof obj[prop] === "function"; });
    names.forEach((k) => methods.add(k));
  }
  return methods;
}

function getAllPropertyNames(object) {
  let properties = new Set();

  for(let obj = object; obj !== null && typeof obj.__proto__ !== null; obj = Object.getPrototypeOf(obj)) {
    let names = Object.keys(obj)
    names.forEach((k) => properties.add(k));
  }
  return properties;
}

let first = new First();
let second = new Second();
let third = new Third();

console.log(getAllPropertyNames(first));
console.log(getAllMethodNames(first));
console.log(getAllStaticMethodNames(First));
console.log(getAllPropertyNames(second));
console.log(getAllMethodNames(second));
console.log(getAllStaticMethodNames(Second));
console.log(getAllPropertyNames(third));
console.log(getAllMethodNames(third));
console.log(getAllStaticMethodNames(Third));
5
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4