Accessing a variable from another function without creating global variables

I recently started using CasperJS to automate websites and something confuses me a little.

How do I access local variables from one function to another? For example:

casper.start('http://google.com', function(){
    var someVar = 20;
});

casper.thenOpen('http://google.com/analytics', function(){
    // How can I access someVar?jav
});

      

I know it is someVar

not in the scope of the second function, but how do I access the someVar

second function without defining global variables?

+3


source to share


3 answers


Without using globals you say, then create a third function (bean) that has a local variable var someVar = 20;

and provides functions getter

and setter

for others to use.



var SharedSpace = (function(){
 var shared = 20; //initialization
 return {
   getShared: function(){
                      return shared;
                   },
   setShared: function(val){
                      shared = val;
                   }
   }
})();

(function(){
    alert(SharedSpace.getShared());
    SharedSpace.setShared(500)
})();

(function(){
    alert(SharedSpace.getShared());
    SharedSpace.setShared(400)
})();

(function(){
    alert(SharedSpace.getShared());
    SharedSpace.setShared(10)
})();
      

Run codeHide result


+1


source


How about using an object to get a specific variable as a property:



var myObj = {};

casper.start('http://google.com', function(){
    myObj.someVar = 20;
});

casper.thenOpen('http://google.com/analytics', function(){
    console.log(myObj.someVar);
});

      

+2


source


You cannot do this to keep it clean and meaningful. Defining a global variable is the only clean way. You could of course put a variable in an object casper

, but this is not that easy as it can interfere with CasperJS functions if you use the wrong variable names. I only do this when defining helper functions for casper

.

casper.start('http://google.com', function(){
    this.someVar = 20;
});

casper.thenOpen('http://google.com/analytics', function(){
    this.echo(this.someVar);
});

      

0


source







All Articles