title: How can I reuse a variable populated within a casperJS call in a subsequent call?
body: <p>I have the following scoping problem in a CasperJS script. baseTargetUrl is undefined when passing into casper.thenOpenAndEvaluate(). Why is this and how can I work around it? </p>
  
  <pre><code>var baseTargetUrl;
          .....
  casper.then(function() {
      baseTargetUrl = this.evaluate(function() {
          return __utils__.getElementByXPath('//*[@id="wrapper"]/div[1]/a[2]')["href"];
      });
      console.log('logging: '+baseTargetUrl); // works
  });
  
  casper.thenOpenAndEvaluate(baseTargetUrl ,function() { //baseTargetUrl is undefined here
      var test = document.querySelector('myselector');
      //do other stuff
  
  });
  </code></pre>