如何在另一个函数中访问局部函数变量
var objectTest=
{
test1: function( )
{
val1 = 1;
},
// hows accessing the
test2: function( )
{
alert( val1 );
}
};
objectTest.test2( );
var objectTest=
{
test1: function( )
{
val1 = 1;
},
// hows accessing the
test2: function( )
{
alert( val1 );
}
};
objectTest.test2( );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过不使用前缀 var ,变量被放入不同的(全局)范围尝试:
正如 @Pekka 指出的,您的示例(上面)需要调用 objectTest.test1();首先(创建
val1
),否则您会收到错误。如果您想要从两个地方访问变量,那么您应该使用不会添加到全局范围的对象属性(如@patrick dw建议)By not using the prefix
var
the variable is put in different (global) scope try instead:As @Pekka points out, your example (above) requires the calling of
objectTest.test1();
first (to createval1
) otherwise you'll get an error. If you want to access the variable from both places, then you should rather be using an object-property (like @patrick dw suggests) which doesn't add to the global scope不可以。两个函数不能同时运行,因此不可能按照您显示的方式共享本地范围。您必须将
val1
定义为对象的成员。It can't. Two functions can't run at the same time, so sharing local scope is impossible the way you show. You would have to define
val1
as a member of the object.取决于你最终想要做什么。您可以将其设为对象的公共成员:
示例: http://jsfiddle.net/ wqr6W/
这当然会改变你原来的代码。您实际需要做什么取决于您的具体情况。
或者这样:
示例: http://jsfiddle.net/wqr6W/1/
Depends on what you ultimately want to do. You could make it a public member of the object:
Example: http://jsfiddle.net/wqr6W/
This of course changes your original code. What you actually need to do will depend on your circumstance.
Or this:
Example: http://jsfiddle.net/wqr6W/1/
添加另一个答案以便更直接地回答问题。
如果您实际上谈论的是函数的本地变量,那么简单的答案是您不能访问它除非您传递一个函数具有变量的函数的名称,它引用该变量。
这称为创建闭包。
示例: http://jsfiddle.net/csd3s/
所以在
内test2
您可以调用test1()
函数,该函数返回一个包含函数的对象,该函数引用局部变量。这(或类似的东西)就是在函数中引用其他不可访问的局部变量所需要的。
Adding another answer in order to more directly answer the question.
If you are actually talking about a local variable to a function, the simple answer is that you can not access it unless you pass a function out of the function that has the variable, which makes reference to the variable.
This is called creating a closure.
Example: http://jsfiddle.net/csd3s/
So inside
test2
you can call thetest1()
function, which returns an object that contains a function, which references the local variable.That (or something similar) is what it takes to reference an otherwise non-accessible local variable in a function.