JS私有方法和变量

494 阅读1分钟

Private Variables

此方法有个缺点,就是每次创建一个新实例都会重新创建一个新方法

function MyObject(){
    //private variables and functions var privateVariable = 10;
    function privateFunction(){ 
        return false;
    }
    //privileged methods 
    this.publicMethod = function (){
        privateVariable++;
        return privateFunction(); 
    };
}


function Person(name){
    this.getName = function(){ 
        return name;
    };
    this.setName = function (value) { 
        name = value;
    }; 
}
var person = new Person(“Nicholas”); 
alert(person.getName()); //”Nicholas” 
person.setName(“Greg”); 
alert(person.getName()); //”Greg”

Static Private Variables

没有var关键字,MyObject默认为全局变量。 此方法的缺点是会共用匿名函数里面的变量

(function(){
    //private variables and functions 
    var privateVariable = 10;
    function privateFunction(){ return false;}
    //constructor
    MyObject = function(){ };
    //public and privileged methods MyObject.prototype.publicMethod = function(){
        privateVariable++;
        return privateFunction(); 
    };
})();


(function(){
    var name = “”;
    Person = function(value){ name = value;};
    Person.prototype.getName = function(){ return name;};
    Person.prototype.setName = function (value){ name = value;}; 
})();
var person1 = new Person(“Nicholas”); 
alert(person1.getName()); //”Nicholas” 
person1.setName(“Greg”);
alert(person1.getName()); //”Greg”
var person2 = new Person(“Michael”); 
alert(person1.getName()); //”Michael” 
alert(person2.getName()); //”Michael”

The Module Pattern


var singleton = function(){
    //private variables and functions var privateVariable = 10;
    function privateFunction(){
        return false;
    }
    //privileged/public methods and properties 
    return {
        publicProperty: true,
        publicMethod : function(){ 
            privateVariable++;
            return privateFunction();
        }
    };
}();