gpt4 book ai didi

javascript - 无法访问资源请求的回调函数内的变量

转载 作者:行者123 更新时间:2023-12-03 02:11:11 24 4
gpt4 key购买 nike

如何将变量从外部传递到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 值,相当于将 this 视为闭包值。

关于javascript - 无法访问资源请求的回调函数内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49565001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com