无法访问 Resource Requested 回调函数中的变量

Not able to access varaible inside the callback function of onResourceRequested

如何将变量从外部传递给onResourceRequested函数? 我无法在 onResourceRequested 属性 的回调函数中访问变量 testvar

知道如何解决这个问题吗?

下面是我用来测试的示例代码

var phantom = require("phantom");

var _ph, _page, _outObj;



phantom.create().then(function(ph){
    _ph = ph;
    return _ph.createPage();
}).then(function(page){
    _page = page;
    var testvar = "WHY THIS IS NOT PRINTING";

    _page.property('onResourceRequested', function (req, networkRequest) {
        console.log("THIS LINE WORKS");
        console.log(testvar); // THIS DOESNT WORK
    }); 

    _page.property('onResourceReceived', function (res) {
         //console.log('received: ' + JSON.stringify(res, undefined, 4));
    });

    return _page.open('https://www.ammaus.com/', function (status) {
        if (status !== 'success') {
            console.log('FAIL to load the address');
        }
        _ph.exit();
    });

}).then(function(status){
    console.log(status);
    return _page.property('content')
}).then(function(content){
    _page.close();
    _ph.exit();
}).catch(function(e){
   console.log(e); 
});

像这样使用箭头函数 (ES6):

_page.property('onResourceRequested', (req, networkRequest) => {
    console.log("THIS LINE WORKS");
    console.log(testvar); // THIS DOESNT WORK
});

箭头函数在全局上下文中执行时不会重新定义它自己的 this;相反,使用封闭执行上下文的 this 值,相当于将其视为闭包值。