Search code examples
javascriptglobal-variablesjavascript-objectsnested-function

How to access globar variable with nested functions ? javascript


I have the bellow class:

var CasperInstance = function(casper) {

    this.casper = casper;
    var x = casper.selectXPath;
    var parent = this;


    this.then = function(callback) {

        return this.casper.then(function() {

            parent.casper.evaluate(function() {

                try {
                    x('//*[@id="email_address"]');
                } catch (err) {

                    //ReferenceError: Can't find variable: x
                    console.log(err);
                }

            });

        });

    };


};

When i try to call the x() , I get this error:ReferenceError: Can't find variable: x .

however x is global variable I can access from any nested function . right ?

Thank you


Solution

  • This is a common problem when using things like Casper.

    Normally a javascript function would capture x in a closure and it would be available to functions within the scope. That's what it looks like should happen here. But the problem is that casper.evaluate() specifically avoids this -- the point of evaluate() is to use the context of the current page DOM. Which means you only have access to the scope of the page. The documentation is actually very good on this point:

    http://docs.casperjs.org/en/latest/modules/casper.html#evaluate

    You aren't going to be able to pass a function into casper.evaluate. evaluate() is basically calling phantomjs's evaluate(), so their docs are helpful:

    Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

    So you are kind of stuck and will need to find a different way to do this.