Skip to content

Instantly share code, notes, and snippets.

@petamoriken
Last active March 7, 2020 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petamoriken/bb99ca136bc663d3c6ac to your computer and use it in GitHub Desktop.
Save petamoriken/bb99ca136bc663d3c6ac to your computer and use it in GitHub Desktop.
EventTarget constructor が使えないときに無理矢理 EventTarget クラスを作るコード。
class MyEventTarget extends DocumentFragment {
constructor() {
super();
Object.setPrototypeOf(this, EventTarget.prototype);
}
static [Symbol.hasInstance](instance) {
return instance instanceof EventTarget;
}
}
@petamoriken
Copy link
Author

一応どれが速いか計測してみた。

for (const key of Object.getOwnPropertyNames(window)) {
  const target = window[key];
  if (!(target instanceof Function)) { continue; }
  if (target.prototype == null) { continue; }
  if (!(target.prototype instanceof EventTarget)) { continue; }

  try {
    new target();
    console.log(key);
  } catch {}
}

で一覧を取得して jsPerf に投げてみた。
https://jsperf.com/eventtarget

DocumentFragmentCommentText あたりが速そうだった。

@petamoriken
Copy link
Author

petamoriken commented Mar 7, 2020

const source = `
for (const key of Object.getOwnPropertyNames(self)) {
  const target = self[key];
  if (!(target instanceof Function)) { continue; }
  if (target.prototype == null) { continue; }
  if (!(target.prototype instanceof EventTarget)) { continue; }

  try {
    new target();
    console.log(key);
  } catch {}
}
`;
const blob = new Blob([source], { type: "text/javascript" });
const url = URL.createObjectURL(blob);
new Worker(url);

Worker 内だと FileReader かな。

@petamoriken
Copy link
Author

petamoriken commented Mar 7, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment