繁体   English   中英

如何使用对象存储全局变量? 最佳实践

[英]How to use objects for storing global variables? Best practice

我是JavaScript的OOP新手,因为我总是使用一些框架和我自己的简单结构,但从未考虑过引擎盖下发生的事情。 现在,我想解决许多JS程序员面临的一个问题 - 全局变量。 我知道制作全局变量是一种不好的做法,许多建议使用对象。 这就是问题突然出现的地方。 我不知道创建对象的最佳方法是什么,并在应用程序中的某处调用它来获取全局变量值。 例如,我不确定是否使用init函数以及如何返回全局变量值(通过函数或“点”表示法)。 我见过很多关于物体的例子,但它们的风格看起来不一样。 想象一个具体的例子。 我想将全局变量存储在一个对象中 - 窗口的高度和窗口的宽度。 为了使它跨浏览器,我将使用此代码

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    w = w.innerWidth || e.clientWidth || g.clientWidth, // this is global variable
    h = w.innerHeight|| e.clientHeight|| g.clientHeight; // and this is global varibale too

那么,如何在abject中应用此代码以及如何在应用程序中的某处获取这些全局变量的值?

编辑

现在,我的代码如下所示:

var module = (function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
width = w.innerWidth || e.clientWidth || g.clientWidth,
height = w.innerHeight || e.clientHeight || g.clientHeight;
return {
  getHeight:function(){
     return height;
  },
  getWidth:function(){
     return width;
  }
}
}());

要访问heightwidth属性,我调用getHeightgetWidth方法。 对我来说唯一看起来很奇怪的是重叠return这些returns 这是一种正确的方法吗?

我建议你避免全球

全局变量是一个非常糟糕的主意。

原因:您的代码被您添加到页面后的任何其他JavaScript覆盖的危险。

解决方法:使用闭包和模块模式

示例代码解释模块和闭包

module = function(){
   var current = null;
   var labels = {
      'home':'home',
      'articles':'articles',
      'contact':'contact'
   };
   var init = function(){
   };
   var show = function(){
      current = 1;
   };
   var hide = function(){
      show();
   }
   return{init:init, show:show, current:current}
}();
module.init();

你的代码:

var module = (function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
width = w.innerWidth || e.clientWidth || g.clientWidth,
height = w.innerHeight || e.clientHeight || g.clientHeight;
    var getWidth = function(){
        console.log(width);
        return width;
}
    var getHeight = function(){
        console.log(height);
        return height;
}
    return{getWidth:getWidth, getHeight:getHeight}
}());
module.getHeight();
module.getWidth();

DEMO FIDDLE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM