码迷,mamicode.com
首页 > 编程语言 > 详细

《javascript设计模式与开放实践》学习(四)私有变量

时间:2016-09-29 01:49:02      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

为了避免全局变量被污染,可采用加命名空间和闭包封装方式进行私有化。

一、使用命名空间

将某个变量变成某个命名空间下私有变量

var MyApp={};
    MyApp.namespace=function (name) {
        var parts=name.split(‘.‘);
        var current=MyApp;
        for(var i in parts){
            if(!current[parts[i]]){
                current[parts[i]]={};
            }
            current=current[parts[i]];
        }
    };
    MyApp.namespace(‘event‘);
    MyApp.namespace(‘dom.style‘);

    console.dir(MyApp);

上述等价于

var Myapp={
        event:{},
        dom:{
            style:{}
        }
};

这样就定义了MyApp命名空间下的两个属性event和dom.

二、使用闭包

 var user=(function () {
        var _name=‘ls‘,
        _age=27;
        return{
            getUserInfo:function () {
                return _name+‘_‘+_age;
            }
        }
    })();
    console.log(user.getUserInfo()) ;

将name和age属性封装起来,外部无法访问。

《javascript设计模式与开放实践》学习(四)私有变量

标签:

原文地址:http://www.cnblogs.com/GallopingSnail/p/5918266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!