Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript calling a inner function from outside

Tags:

javascript

This is regarding javascript closures working. I have a function inside another and I want to access this outside of the outer function. is it possible since it written here that u can achieve closure with this http://www.w3schools.com/js/js_function_closures.asp JavaScript Nested Functions All functions have access to the global scope.

In fact, in JavaScript, all functions have access to the scope "above" them.

JavaScript supports nested functions. Nested functions have access to the scope "above" them.

In this example, the inner function plus() has access to the counter variable in the parent function:

Example

function add() {
    var counter = 0;`enter code here`
    function plus() {counter += 1;}
    plus();    
    return counter; 
}

I am trying to acess plus() from outside

like image 341
Rahul Kumar Jain Avatar asked Aug 09 '26 13:08

Rahul Kumar Jain


2 Answers

Agree with Grim.

But if you wanna access to plus function outside, you can try this way:

function add(){
  var counter = {
      value: 0,
      plus: function(){
         return ++this.value;
      }
  };
  counter.plus();
  return counter; 
}

Hope it helps.

like image 102
Teddy Avatar answered Aug 11 '26 06:08

Teddy


You cannot. An inner function is only available within the body of the outer function.

like image 43
Grim... Avatar answered Aug 11 '26 06:08

Grim...