1

I have two functions one and two, where function one calls in second function but it doesn't work,

for example:

function one() {
 var a = 1;
 var position = {
  global: function(b) {
    console.log(b);
  }
 }
}

function two(){
 $(window).on('swipedown', function() {
   one();
   position.global(a);
});
}

two();

demo`

jsfiddle

3
  • 4
    You need to declare both a and position in a shared scope Commented Oct 6, 2015 at 9:36
  • 1
    jsfiddle.net/arunpjohny/ca9sz05w/1 Commented Oct 6, 2015 at 9:36
  • Other way would be to make your function returning relevant variables if you don't want to pollute the outer scope Commented Oct 6, 2015 at 9:42

2 Answers 2

1

You need to declare the a and position object outside the function to avoid closure.

var a = null, position = {};

function one() {
  a = 1;
  position = {
  global: function(b) {
    console.log(b);
  }
 }
}

function two(){
 $(window).on('swipedown', function() {
   one();
   position.global(a);
});
}

two();
Sign up to request clarification or add additional context in comments.

Comments

0

The problem here is the scope of the variables a and position, since you have declared them in the function one, it exists only inside that function, once the function is exited the variables are no longer available.

Since you are accessing the variables in function two, you need to declare them in a shared scope like

var position, a;

function one() {
  a = 1;
  position = {
    global: function(b) {
      snippet.log('b:' + b);
    }
  }
}

function two() {
  $(window).on('scroll', function() {
    one();
    position.global(a);
  });
}

two();
body {
  height: 3000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


Another way to use the variable a is to make use of closure like

var position;

function one() {
  var a = 1;
  position = {
    global: function() {
      snippet.log('a:' + a);
    }
  }
}

function two() {
  $(window).on('scroll', function() {
    one();
    position.global();
  });
}

two();
body {
  height: 3000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.