13

モジュール パターンを実装するとき、プライベート関数はモジュールのプライベート プロパティにどのようにアクセスしますか? 開発者がこれを行う例は見たことがありません。しない理由はありますか?

var module = (function(){
    // private property
    var number = 0;

    // private method
    _privateIncrement = function(){
        // how do I access private properties here?
        number++;
    };

    // public api
    return {
        // OK
        getNumber: function(){
             return number;   
        },
        // OK
        incrNumber: function(){
             number++;  
        },
        // Doesn't work. _privateIncrement doesn't have
        // access to the module's scope.
        privateIncrNumber: function(){
            _privateIncrement();
        }
    };
})();
4

2 に答える 2

13

モジュール パターンを実装する場合、プライベート関数はモジュールのプライベート プロパティにどのようにアクセスしますか?

プロパティはスコープ内にあるため、「実行するだけ」です

うまくいきません。

はい、そうです。

_privateIncrementモジュールのスコープにアクセスできません。

はい、そうです。

次の実際の例を参照してください。

var module = (function(){
    // private property
    var number = 0;

    // global method
    _privateIncrement = function(){
        number++;
    };

    // public api
    return {
        // OK
        getNumber: function(){
             return number;   
        },
        // OK
        incrNumber: function(){
             number++;  
        },
        // Does work!
        privateIncrNumber: function(){
            _privateIncrement();
        }
    };
})();

// Show default value
document.body.innerHTML += (module.getNumber());
// Increment
module.privateIncrNumber();
// Show new value
document.body.innerHTML += (module.getNumber());
// Increment (since _privateIncrement was defined as a global!)
_privateIncrement();
// Show new value
document.body.innerHTML += (module.getNumber());

// Output: 012
于 2011-12-20T18:11:09.137 に答える
3

にアクセスできるプライベート メソッドを使用する 1 つの代替方法は、またはメソッドthisを使用することです。callapply

function Restaurant()
{
    this.mongoose = 'beans';
    this.freedom = {bear:'love',a:'12'};

    var myPrivateVar;

    var private_stuff = function()   // Only visible inside Restaurant()
    {
        myPrivateVar = "I can set this here!";
        this.mongoose = 12;
    }

    this.use_restroom = function()   // use_restroom is visible to all
    {
        private_stuff();
    }

    this.buy_food = function()    // buy_food is visible to all
    {
        private_stuff();
    }

    private_stuff.call(this);
}

var bobbys = new Restaurant();

もちろん、このオブジェクトの複数のインスタンスを持つことを計画している場合は、use_restroom と buy_food をコンストラクターの外のプロトタイプと private_stuff に移動します。

于 2013-10-29T18:43:40.063 に答える