Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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>

以上。

39_isao
鮭とメロンパンとコーヒー牛乳が好物です。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした