我应该使用window.variable还是var? [英] Should I use window.variable or var?

查看:128
本文介绍了我应该使用window.variable还是var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有很多设置JS代码,它们定义了面板,按钮等,这些代码将用于许多其他JS文件。



通常,我们执行如下操作:



grid.js
$ b

  var myGrid = ..... 

combos.js

  var myCombo = ..... 

然后,在我们的应用程序代码中,我们:

application.js

 函数blah(){
myGrid.someMethod()
}

someother.js

  function foo ){
myCombo.someMethod();
myGrid.someMethod();





$ b因此,我们应该使用 var myGrid 或更好地使用 window.myGrid



有什么区别?

解决方案

我会建议创建一个命名空间变量 var App = {};

  App.myGrid = ... 

编辑:关于变量问题的数量 - 想到两种可能的解决方案:

这样你可以限制全局名称空间的污染。


  1. 您可以按类型(网格,按钮等)或关系(ClientInfoSection,AddressSection等)进一步命名空间

  2. 将您的方法封装在使用您拥有的组件实例化的对象中

p>

  function foo(){
myCombo.someMethod();
myGrid.someMethod();

变成:

  var Foo = function(combo,grid){
var myCombo = combo; //将是一个私有属性
this.myGrid = grid; //将是公共属性
this.foo = function(){//公共方法
myCombo.someMethod();
myGrid.someMethod();
}
}
App.myFoo = new Foo(someCombo,someGrid);
App.myFoo.foo();

通过这种方式,您可以限制小对象的数量,并且只显示您需要的数据(即foo函数)



PS:如果您需要公开内部组件,那么将它们添加到构造函数中。


We have a lot of setup JS code that defines panels, buttons, etc that will be used in many other JS files.

Typically, we do something like:

grid.js

var myGrid = .....

combos.js

var myCombo = .....

Then, in our application code, we:

application.js

function blah() {
    myGrid.someMethod()
}

someother.js

function foo() {
    myCombo.someMethod();
    myGrid.someMethod();
}

So, should we be using the var myGrid or is better to use window.myGrid

What's the difference?

解决方案

I would suggest creating a namespace variable var App = {};

App.myGrid = ...

That way you can limit the pollution of the global namespace.

EDIT: Regarding the number of variables issue - 2 possible solutions come to mind:

  1. You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc)
  2. You encapsulate your methods in objects that get instantiated with the components you have

ex: you have

function foo() {
    myCombo.someMethod();
    myGrid.someMethod();
}

becomes:

var Foo = function(combo, grid) {
    var myCombo = combo;//will be a private property
    this.myGrid = grid;//will be a public property
    this.foo = function() {//public method
        myCombo.someMethod();
        myGrid.someMethod();
    }
}
App.myFoo = new Foo(someCombo, someGrid);
App.myFoo.foo();

this way you limit the amount of little objects and only expose what you need (namely the foo function)

PS: if you need to expose the internal components then add them to this inside the constructor function

这篇关于我应该使用window.variable还是var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆