LoginSignup
2
2

More than 5 years have passed since last update.

getter が定義されているクラスプロパティだけを列挙したかった

Posted at

最近は AWS Lambda 上の Node.js で動くアプリケーションづくりをしているのだけど、まぁ掲題のようなことをしたいと思いたって書いたので残しておく。

listupGetter.js
'use strict';

// lodash とかの isFunctionでいいっす
const isFunction = (any) => {
  const str = Object.prototype.toString.call(any);
  return /^\[object (Generator)?Function\]$/.test(str);
}

const listupGetter = (obj) => {
  // プロトタイプ(クラス)取得
  const proto = Object.getPrototypeOf(obj);

  // Object.getOwnPropertyNames: プロトタイプ(クラス)で定義されているプロパティを全部取得
  return Object.getOwnPropertyNames(proto).filter((v) => {
    // そのうち、デスクリプタとして get があるものだけフィルタリング
    const descriptor = Object.getOwnPropertyDescriptor(proto, v);
    return isFunction(descriptor.get);
  });
}

isFunction(descriptor.get) のところを書き換えれば setter だけ取ったりも出来る。

2
2
0

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
2
2