JS私有方法和变量

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();
        }
    };
}();复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值