しまてく

学んだ技術を書きためるブログ

クラスのprivateなメンバー変数の作り方

こういうやり方するとつくれるよ、という例

function Ninja(){
    this.Initialize.apply(this, arguments);
}

Ninja.prototype = {
    Initialize: function(name, age){
        this.getName = function(){ return name; };
        this.getAge = function(){ return age; };
        this.setName = function(val){ name = val; }
        this.setAge = function(val){ age = val; }
    }
}

var x = new Ninja( "cimadai", 24 );

console.log( x.getName() ); //=> cimadai
console.log( x.getAge() ); //= 24
console.log( x.name ); //=> undefined
console.log( x.age); //=> undefined
x.setName("piyo");
x.setAge(30);
console.log( x.getName() ); //=> piyo
console.log( x.getAge() ); //=> 30


やってることは関数スコープを利用したクロージャによる隠ぺいですね。