2012-01-25 38 views
1
(function(){  
     pm.view.someFunction(arg) { 
      arg is used here. 
     }  

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

如何在我的其他函数中传递相同的参数。我听说在关闭时我们可以访问高于其上下文的变量。如何在范围内访问另一个函数中的变量

+1

你确定吗?这是无效的JavaScript。 –

+1

如何调用'someFunction'和'otherFun'?你能不能通过他们两个'arg'? –

+0

BTW:'pm.view.otherFun(){'不是有效的JavaScript。 –

回答

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被声明在函数之外时才可以访问它,比如在strFunc之前如何声明str

1

如果将arg声明为全局变量,那么我不会看到问题出在哪里。 如果没有,为什么不从pm.view.someFunction内拨打pm.view.otherFun

相关问题