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?
source to share
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)
})();
source to share
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);
});
source to share