如何在范围内的另一个函数中访问我的变量

时间:2012-01-25 15:41:53

标签: javascript

(function(){    
        pm.view.someFunction(arg) {
          arg is used here.
        }    

        pm.view.otherFun(){
          how can i pass the same arg here too
        }    
})();

如何在我的其他函数中传递相同的arg。我听说在闭包中我们可以访问高于其上下文的变量。

2 个答案:

答案 0 :(得分:2)

闭包意味着函数可以使用其外部作用域中的变量。这是一个例子:

function test(){
   var str = 'Hello',
   strFunc = function(){
     var s = str + ' world!';
     return s;
   };
   return strFunc;
}
var t = test();
console.log(t()); // Hello world!

teststrFunc)返回的函数是一个闭包。它围绕局部变量str“关闭”。 strstrFunc之外声明,但由于它位于同一范围内,因此可以访问它。

在您的示例中,您只有两个函数(其中一个接受arg参数),它们位于相同的范围内。 arg仅在someFunction的范围内,otherFun无法访问它,除非它作为参数传递,或者arg在函数之外声明,如如何在str之前声明strFunc

答案 1 :(得分:1)

如果arg被声明为全局变量,我看不出问题出在哪里。 如果没有,为什么不在pm.view.otherFun内致电pm.view.someFunction