23
22

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.

JavaScript 手軽にモジュール化する方法メモ

Posted at

jsで手軽にモジュール化する方法のメモです。

名前空間を作ったり、
ちゃんとしたモジュールパターンの記事などはこちら
http://qiita.com/Im0_3/items/3d46f900aa4d4c5c3cde
http://qiita.com/KENJU/items/a8a1009f5872a8b12568

kissメソッド、
hugメソッドなどを持っている、
Loveというモジュールの例です。微妙ですが。

即時関数でくくって作ります。

module.js
var Love = (function(w, d){
    return{
        kiss:function(){
            console.log("キッスします");
        },
        hug:function(){
            console.log("ハグします");
        },
        // pタグの中身を「愛」に変更するメソッド
        changeTextLove:function(){
            var list = d.querySelectorAll('p');
            for(var i = 0; i<list.length; i++){
                list[i].innerHTML = "";
            }
        }
    };
})(window, window.document);

使い方は普通にモジュール化したjsを読み込んで、
Love.kiss();
Love.hug();
のように使います。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>モジュールの作り方コードメモ</title>
</head>
<body>
    <p></p>
    <p>初恋</p>
    <p>淡い恋</p>

    <!-- モジュール読み込み -->
    <script src="module.js"></script>

    <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        Love.kiss(); // キッスします
        Love.hug(); // ハグします
        Love.changeTextLove();
    });
    </script>

</body>
</html>

以上。

23
22
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
23
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?