1

現在のプロジェクトで大量の JavaScript コードを作成および管理する必要があります。

主にモジュールに基づいて、それらを複数の .js ファイルに分割します。

だから、今私は例えば:

Map.js // deal with google map issue
Common.js // common functions that will share by all modules
User.js // user module js code
Geofence.js // geofence module js code
etc.....

たとえば、私の User.js ファイル内

User.js ファイル内でのみ使用され、外部からはアクセスできない関数を宣言したい場合はどうすればよいでしょうか。私に何ができる?

var User = {};

User.registerModule = function () {
    $('#user').click(function () {
        Common.showLeftScrollbar();

        getAllUsers();

        // ...
    });
}

function getAllUsers(){ // how to hide this function
    // get
    return users;
}

したがって、私のホームページでは、複数の .js ファイルを調整するだけで済みます。アクセスを許可するものにアクセスします。

  $(document).ready(function (data) {

        GoogleMap.initialiseGoogleMap();

        Common.refreshRightScrollbar();

        User.registerModule();

        // ...
    });

js を書くのは初めてで、本全体を勉強するのに十分な時間ではありません。それで、あなたの意見では、この構造は多くの js コードで問題ありませんか? また、外部からアクセスしたくない機能を非表示にする方法は?

4

2 に答える 2

3

その機能を非表示にするには、さまざまな可能性があります

  1. すぐに自己実行される匿名関数でコードを囲むだけです

    var User = {}; // this should not be enclosed too
    
    (function() {
        User.registerModule = function () {
            $('#user').click(function () {
                Common.showLeftScrollbar();
    
                getAllUsers();
    
                // ...
            });
        }
    
        function getAllUsers(){ // how to hide this function
            // get
            return users;
        }
    })();
    
  2. その関数を関数内に囲みUser.registerModuleます

    User.registerModule = function () {
        function getAllUsers() { ... }
    
        $('#user').click(function () {
            Common.showLeftScrollbar();
    
            getAllUsers();
    
            // ...
        });
    }
    
于 2012-05-11T08:19:53.633 に答える
1

この関数をスコープ内に配置します。

User.registerModule = function () {
    function getAllUsers(){ // how to hide this function
        // get
        return users;
    }
    $('#user').click(function () {
        Common.showLeftScrollbar();

        getAllUsers(); // returns users

        // ...
    });
}

そして非公開になります。

この関数を外部で呼び出そうとすると、次のようになりますundefined

getAllUsers(); // undefined.
于 2012-05-11T08:15:55.103 に答える