Javascript 局部变量声明

发布于 2024-07-27 00:30:22 字数 474 浏览 3 评论 0原文

基本上这是一个如何访问本地作用域处理程序的问题。 我试图实现类似的全局变量定义,例如:

window['newObject'] = "some string";
alert(newObject);

但对于局部范围。 现在我唯一的解决方案是使用 evals:

eval("var newObject='some string'");

但这确实是一个丑陋的解决方案...最好的解决方案就像在 window[] 解决方案中使用一些对本地范围的引用,但我从未听说过任何对本地范围的引用。 .. 有任何想法吗 ?

示例如下:

function x(arg)
{
   localScope[arg.name]=arg.value;
   alert(sex);
}

x({name:"sex", value:"Male"});

Basically this is a question how to access local scope handler. I trying to achieve something similar for global variable definition like:

window['newObject'] = "some string";
alert(newObject);

but for local scope. Right now only solution I have is using evals:

eval("var newObject='some string'");

But this is really ugly solution... The best one would be like using some reference to local scope like in a window[] solution, but I never heard of any reference to local scope... Any ideas ?

Example goes here:

function x(arg)
{
   localScope[arg.name]=arg.value;
   alert(sex);
}

x({name:"sex", value:"Male"});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

山川志 2024-08-03 00:30:22

您正在寻找的内容称为调用对象。 但根据 这个,您无法直接访问它,所以你运气不好。

What you're looking for is called the call object. But according to this, you can't access it directly, so you're out of luck.

纵性 2024-08-03 00:30:22

为什么不在本地范围内创建一个对象,然后将其用作您希望动态创建的任何变量的容器?

function x(arg)
{
    var localSpace = {};
    localSpace[arg.name] = arg.value;
}

Why not create an object in local scope and then use it as a container for any variables you wish to create dynamically?

function x(arg)
{
    var localSpace = {};
    localSpace[arg.name] = arg.value;
}
虐人心 2024-08-03 00:30:22

好吧,我发现相关的问题正在讨论我需要什么...

如何在 javascript 中动态访问本地作用域?

我只记得在 ECMA 262 中只是使用“with”语句(当然还有 eval)将动态本地变量添加到作用域的一种方法,以下是解决方案:

var x=function(obj)
{

    with(obj) 
    {
       alert(someObj);
    }
 }
 alert(typeof someObj);


 x ( {someObj:"yea"}) ;

 alert(typeof someObj);

Okey I found related question that is talking about what I need...

How can I access local scope dynamically in javascript?

I just remember that in ECMA 262 is only one way to add dynamically local variables to scope using "with" statement (and eval of course), here are solution:

var x=function(obj)
{

    with(obj) 
    {
       alert(someObj);
    }
 }
 alert(typeof someObj);


 x ( {someObj:"yea"}) ;

 alert(typeof someObj);
你在我安 2024-08-03 00:30:22

我一定是错过了什么。 你想要的与仅仅做有什么不同:

 var newObject = 'some string';

(OP已澄清问题)

我认为没有办法做到你所要求的。 使用本地对象的成员,例如,

function doSomething(name, value)
{
  var X = {};
  X[name] = value;
  if (X.foo == 26)
    alert("you apparently just called doSomething('foo',26)");
}

如果您选择像 $ 或 X 这样的 1 字符变量,它会“花费”您 2 个字符(变量名加一个点),并避免尝试使用 eval 或做一些奇怪的事情。

I must be missing something. How is what you want different from just doing:

 var newObject = 'some string';

? (OP has clarified question)

I don't think there is a way to do what you are asking. Use members of a local object, e.g.

function doSomething(name, value)
{
  var X = {};
  X[name] = value;
  if (X.foo == 26)
    alert("you apparently just called doSomething('foo',26)");
}

If you choose a 1-character variable like $ or X, it "costs" you 2 characters (variable name plus a dot), and avoids trying to use eval or doing something weird.

从此见与不见 2024-08-03 00:30:22

您可以尝试命名参数技巧
编辑:这不是跨浏览器

function x( {sex:sex, height:height} ) {
    alert( sex );
    alert( height );
}

x( { sex: 'male', height: 'short' } );
x( { height: 'medium', sex: 'female' } );

// male
// short
// female
// medium

You could try the named arguments trick
EDIT: This isn't cross browser

function x( {sex:sex, height:height} ) {
    alert( sex );
    alert( height );
}

x( { sex: 'male', height: 'short' } );
x( { height: 'medium', sex: 'female' } );

// male
// short
// female
// medium
悲歌长辞 2024-08-03 00:30:22

不确定你到底需要什么,但这是我的 2 美分。

在现有函数中动态创建变量的唯一方法是您已经提到的 eval 方法。

另一个选项(其他人提到的)是您的函数采用上下文映射,模板使用点符号(context.var1)访问它。

我最后的建议是 Function 构造函数。 但我有一种感觉,这可能就是您正在寻找的。 (请注意,函数构造函数遇到与 eval 调用相同的问题)

var arg1 = "first";
var arg2 = "last";

// This is the body of the function that you want to execute with first
// and last as local variables. It would come from your template
var functionBody = "alert(first + ' ' + last)";

var myCustomFun = new Function(arg1, arg2,  functionBody);

myCustomFun("Mark", "Brown"); // brings up and alert saying "Mark Brown";

希望有帮助

Not sure what you need exactly, but here's my 2 cents.

The only way to dynamically create vars in an existing function is the eval method you've already mentioned.

Another option (mentioned by others) is that your function take a context map, and the template access it with dot notation (context.var1)

My final suggestion is the Function constructor. But I have a feeling this may be what you're looking for. (Note that the function constructor suffers from the same problems as an eval call)

var arg1 = "first";
var arg2 = "last";

// This is the body of the function that you want to execute with first
// and last as local variables. It would come from your template
var functionBody = "alert(first + ' ' + last)";

var myCustomFun = new Function(arg1, arg2,  functionBody);

myCustomFun("Mark", "Brown"); // brings up and alert saying "Mark Brown";

Hope it helps

我的影子我的梦 2024-08-03 00:30:22

有趣的问题,从来没有想过这样的事情。 但用例是什么?

您想要执行此类操作的原因是您不知道变量的名称。 但在这种情况下,再次访问变量的唯一方法是使用相同的引用对象。 即,您可以使用任何旧对象来存储数据。

从这样的引用对象中读取数据对于调试目的来说会很有趣,但我不明白您为什么要写入它。

编辑:

您发布的示例并没有让我相信需要访问本地范围,因为您仍然在警报中硬编码了名称sex。 这可以实现为:

function x(arg)
{
  container = {};
  container[arg.name] = arg.value;
  alert(container.sex);
}

您能详细说明一下这个例子吗?

Interesting question, never thought of something like this. But what is the usecase?

The reason you'd want to do something like this, is if you don't know the name of the variable. But then in that case, the only way to access the variable again would be using the same reference object. I.e. you could just use any old object to store data in.

Reading from such a reference object would be interesting for debugging purposes, but I don't see why you'd want to write to it.

Edit:

The example you posted doesn't convince me of the need for access to the local scope, since you still have the name sex hard coded in the alert. This could be implemented as:

function x(arg)
{
  container = {};
  container[arg.name] = arg.value;
  alert(container.sex);
}

Could you elaborate more on the example?

梦中的蝴蝶 2024-08-03 00:30:22

我不完全确定我理解你的问题。 创建类 x 时,我通常这样做:

function x(args) {
  var _self = this;

  _self.PriviledgedMethod(a) {
      // some code
  }

  function privateMethod(a) {
      // some code
  }
}

var newObject = new x(args);

您可以继续访问 _self 和 args,因为它被包含的函数关闭。

I'm not entirely sure I understand your question. When creating a class x, I generally do this:

function x(args) {
  var _self = this;

  _self.PriviledgedMethod(a) {
      // some code
  }

  function privateMethod(a) {
      // some code
  }
}

var newObject = new x(args);

You can continue to access _self and args since it is closed on by the contained functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文