简体   繁体   中英

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. Is it possible, on what changes i have to make to 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.someName = function(){};

Note that this will work only after the execution of the S.ui.createpulldown function (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

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;

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. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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