简体   繁体   English

在另一个函数内调用函数

[英]calling function inside a another function

S.ui.createpulldown = function() {  
    function someName(){
    }
    someName() // gets called
}
someName() // does not get called, when outside because of scope issue.

I want to call this function outside the s.ui.createpulldown function. 我想在s.ui.createpulldown函数之外调用此函数。 Is it possible, on what changes i have to make to function someName() 我可以对function someName()进行哪些更改?

you have to assign the function to a variable that is visible in the desired scope : 您必须将函数分配给在所需范围内可见的变量:

//...
var someName;
S.ui.createpulldown = function() {  

  someName = function(){

  }

  someName() // gets called

}
someName(); // gets called also
//...

or if you want it to be a global variable (visible in all scopes), you can pin it to the window object : 或者,如果要使其成为全局变量(在所有作用域中可见),则可以将其固定到window对象:

window.someName = function(){};

Note that this will work only after the execution of the S.ui.createpulldown function (thx, pimvdb). 请注意,这仅在执行S.ui.createpulldown函数(thx,pimvdb)后才有效。

This is a scoping problem. 这是一个范围界定问题。 You can't access somefunction because it is a local variable of createPullDown , just like i in the following example 您不能访问somefunction ,因为它是一个局部变量createPullDown ,就像i在下面的例子中

function pulldown(){
    for(var i=0; i<n; i++){ ... }
}

i; //can't use "i" here!

If you want somename to ve visible outside the function you need to declare it outside, or pass it to someone that is visible outside or set a property of an object that is visible outside; 如果要使somename在函数外部可见,则需要在函数外部声明它,或者将其传递给在外部可见的人,或者设置在外部可见的对象的属性;

var someFunction;
var someObj = {};

S.ui.createpulldown = function() {  

   function someName(){

   }

   someFunction = someName;
   someObj.func = someName;

}

S.ui.createpulldown();

someFunction();
someObj.func();

move somename outside the function in which it is defined. somename移到定义它的函数之外。 If you are going to use it in more than one place, put it on the appropriate part of the namespace. 如果要在多个地方使用它,请将其放在名称空间的适当部分。

您不能在s.ui.createpulldown函数之外调用函数someName()

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

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