4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ES2015で即時関数を実行する

Last updated at Posted at 2018-04-02

はじめに

ES2015を用いて「1度だけ実行する関数をimportして使う」モジュールを作るための、備忘録です。
export defaultはclassの冒頭につけるやり方しか知らず、ファイルの中身を即時関数1つだけにしたときにどうすればいいかわかりませんでした。
検索してもうまくヒットしなかったので、備忘録です。

実装

サンプルのコードはPCかどうかを判定して、PCでなければtrueを返すという処理です。

before
const isMobile = function () {
  const ua = window.navigator.userAgent.toLowerCase();
  return /iphone|ipod|ipad|android/.test(ua);
};
module.exports = isMobile;

before.common

import isMobile from 'isMobile';

if(isMobile()){
console.log('spn');
}

このように書くと、importしている部分で毎回関数を実行することになります。
この機能の場合、最初に1度実行すれば毎回実行して確認する必要はありません。
なので、下記のように即時関数にすることで、実行回数を減らすことができます。

after
const isMobile = (() => {
  const ua = window.navigator.userAgent.toLowerCase();
  return /iphone|ipod|ipad|android/.test(ua);
})();
export default isMobile;
after.common

import isMobile from 'isMobile';

if(isMobile){
console.log('spn');
}

おわりに

自分の備忘録のために掲載しました。
もっと効率のよいやり方やパフォーマンスのいいやり方を知っている方がおりましたら教えてください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?