سؤال

I have this strange problem and not able to understand how does the scope of the function works within a file.

E.g.

function f3() {
}

function f2() {
   f3(); // Cannot find variable: f3
}

function f1() {
    f3(); // works fine
    f2(); // works fine
   }

f1();

Edited

Actual Code.

var page = require('webpage').create();

function fPrintObj(obj) {
    // Object properties
    var output = '';
    for (var property in obj) {
        output += property + ': ' + obj[property]+'; ';
    }
    console.log(output);
}

function  fGetXpathAd() {
    xPathAd = "//div[@class='col-xs-12 col-sm-12 col-md-12 col-lg-12 home-solutions-head']";
    console.log(xPathAd);

    var adcopy = document.evaluate( xPathAd, document, null, XPathResult.STRING_TYPE, null);
    fPrintObj(adcopy);  //DOES NOT WORK
    return adcopy;  
}

function main(status) {

        console.log('Evaluating ad-copy.... ');
        var a = page.evaluate(fGetXpathAd);
        // fPrintObj(a);  // WORKS

    phantom.exit();
}

//  fSetRandomUserAgent();
page.open('https://www.position2.com', main );

Error

ReferenceError: Can't find variable: fPrintObj

phantomjs://webpage.evaluate():6 in fGetXpathAd
phantomjs://webpage.evaluate():8
phantomjs://webpage.evaluate():8
هل كانت مفيدة؟

المحلول

In phantomjs, page.evaluate is a page context and you can not call a function defined outside of it. You should pass your function as second argument to the page.evaluate like this:

function  fGetXpathAd(fPrintObj) {
    xPathAd = "//div[@class='col-xs-12 col-sm-12 col-md-12 col-lg-12 home-solutions-head']";
    console.log(xPathAd);

    var adcopy = document.evaluate( xPathAd, document, null, XPathResult.STRING_TYPE, null);
    fPrintObj(adcopy);  //WILL WORK
    return adcopy;  
}

function main(status) {

        console.log('Evaluating ad-copy.... ');
        var a = page.evaluate(fGetXpathAd, fPrintObj);
        // fPrintObj(a);  // WORKS

    phantom.exit();
}

I hope this will help.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top