所以我有以下用于phantomjs:
var time = 1490543999999999;
var endTime = time - 518400000000 * 10;
var mintime = time - 518399999999;
console.log("mintime after assignment is"+mintime);
var loopnumber = 6;
page.open('https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28', callback);
function callback() {
console.log("inside callback and loopnumber is "+loopnumber+"and time is "+time+", and mintime is "+mintime+'. URL: https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28');
page.render('/Users/jMac-NEW/Documents/FILEMAKER OCLC/login_test33.7_brkpoint' + loopnumber + '.png');
fs.write('/Users/jMac-NEW/Documents/FILEMAKER OCLC/login_test33.7_brkpoint' + loopnumber + 'html.html', page.content, 'w');
time -= 518400000000;
loopnumber++;
if (time > endTime) {
var mintime = time - 518399999999;
page.open('https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28', callback);
}
else {
phantom.exit();
}
}
这是第一个console.log:
的输出mintime after assignment is1490025600000000
但是当谈到callback()中的console.log时,这就是输出:
inside callback and loopnumber is 6and time is 1490543999999999, and mintime is undefined. URL: https://myactivity.google.com/item?min=undefined&max=1490543999999999&product=5,6,7,10,11,12,13,15,19,20,25,27,28
为什么mintime = undefined,其他变量(loopnumber和time)不是?
答案 0 :(得分:0)
Javascript中有一个名为 hoisting 的概念 - 如果在之后使用声明变量,则脚本解释器会自动移动它'在内部声明到当前范围的顶部。
所以你的脚本实际上读到这样的js:
function callback() {
var mintime; // <-- declaration moved here
// mintime is not yet defined
console.log("and time is "+time+", and mintime is "+mintime);
// ...
if (time > endTime) {
mintime = time - 518399999999; // it's been declared already and now it's defined
}
else {
phantom.exit();
}
}
所以解决方案很简单:在回调中将var
从赋值中删除到mintime
,这种方式变量将被分配给外部(窗口)范围mintime
,就像你想要的那样。