简体   繁体   English

在javascript中使对象变为非全局对象

[英]Making objects nonGlobal in javascript

I have a function in JavaScript which looks something like this: 我有一个JavaScript函数,看起来像这样:

foo=function(listenerObject)
{
  a={count:0};
  foo2=function(){
    //does stuff with a
  }
  //register listenerObject to callback the function foo2
}

The problem is I end up using this function to register multiple listeners, but they all end up sharing the same 'a' object. 问题是我最终使用此功能注册了多个侦听器,但是它们最终都共享相同的“ a”对象。 Is there a way to keep an object declaration inside a function from creeping into the global scope. 有没有一种方法可以防止函数内部的对象声明爬入全局范围。 In other words I would like to prevent being able to do something like this 换句话说,我想阻止能够做这样的事情

fun=function(){o={count:0}}
o.count++//o is now in the global scope

Use var . 使用var Really, you should be declaring all of your variables with var otherwise you'll, as you found out, get a bunch of global variables stepping on each other. 确实,您应该使用var声明所有变量,否则,您会发现,一堆全局变量互相作用。

Example: 例:

var foo = function(listenerObject) {
  var a = { count: 0 };
  ...
};

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

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