zoukankan      html  css  js  c++  java
  • JavaScript命名空间namespace的实现方法

    网上有很多了,这里给出一个,其实思路就是A={}; A.b={};其实b是A的一个属性。只是做了一些封装,最后的效果是可以直接定义多个namespace:

       1:  My.namespace("Company", "Company.Feed", "Company.Feed.Messaging");

    具体的实现方法,用到了arguments, eval等JavaScript函数

       1:  //namespace的实现
       2:  var MyFramework = {};
       3:   
       4:  MyFramework.namespace=function(){ 
       5:      var a=arguments, o=null, i, j, d, rt; 
       6:      for (i=0; i<a.length; ++i) { 
       7:          d=a[i].split("."); 
       8:          rt = d[0]; 
       9:          eval("if (typeof (" + rt + ") == 'undefined'){" + rt + "= {};} o = "+ rt + ";"); 
      10:          for (j=1; j<d.length; ++j) { 
      11:              o[d[j]]=o[d[j]] || {}; 
      12:              o=o[d[j]]; 
      13:            } 
      14:        } 
      15:    };

    使用方法

       1:  MyFramework.namespace("MyCompany.feed", "IBM.common"); //直接定义多个namespace
       2:                
       3:  MyCompany.feed =
       4:   {
       5:       alert: function (msg) {
       6:           alert(msg);
       7:       },
       8:   
       9:       load: function () {
      10:       }
      11:   
      12:   };
      13:               
      14:  MyCompany.feed.test = function (t){
      15:    alert("MyCompany.feed.test : "+t);
      16:  };
      17:   
      18:  IBM.common.messging = function (t){
      19:    alert("IBM.common.messging: "+t);
      20:  };
      21:   
      22:  MyCompany.feed.test("def");
      23:  MyCompany.feed.alert("abc");    
      24:  IBM.common.messging("fff");
  • 相关阅读:
    如何在 ASP.NET 中(服务器端)主动清除(HTTP内容响应时)浏览器中的 Cookies 数据
    修复 dji spark 的 micro sd/tf 存储卡里不能正常播放的视频文件
    在 Windows 7 中安装 .NET Framework 时遇到错误:无法建立到信任根颁发机构的证书链
    【转】在 Windows 10 下,配置 Kinect v2 可用于 Windows Hello 验证身份
    安装SQL Server提示“等待数据库引擎恢复句柄失败”
    [转]如何禁止 IIS 在 C:WindowsSystem32LogFilesHTTPERR 中生成日志文件
    Kinect v2 记录
    处理 ASP.NET 中的异常:无法在发送 HTTP 标头之后进行重定向。
    在 Windows Server 2008 中部署带 SignalR 的网站出错
    ( ̄▽ ̄)" 关于河北ETC记账卡的默认密码
  • 原文地址:https://www.cnblogs.com/Mainz/p/2119578.html
Copyright © 2011-2022 走看看