JS私有方法和變量

Private Variables

此方法有個缺點,就是每次建立一個新實例都會從新建立一個新方法bash

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();
        }
    };
}();複製代碼
相關文章
相關標籤/搜索