如何使用嵌套函数访问全局变量? javascript
How to access globar variable with nested functions ? javascript
我有波纹管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);
}
});
});
};
};
当我尝试调用 x() 时,出现此错误:ReferenceError: Can't find variable: x
.
但是 x 是我可以从任何嵌套函数访问的全局变量。对吗?
谢谢
x
不是全局变量,它是 casperInstance
函数的局部变量。我建议
this.casper.selectXPath('//*[@id="email_address"]');
这是使用 Casper
.
之类的东西时的常见问题
通常,javascript 函数会在闭包中捕获 x
,并且它可用于范围内的函数。这就是这里应该发生的事情。但问题是 casper.evaluate()
专门避免了这一点 -- evaluate()
的要点是使用当前页面 DOM 的上下文。这意味着您只能访问页面的范围。文档在这一点上实际上非常好:
http://docs.casperjs.org/en/latest/modules/casper.html#evaluate
您将无法将函数传递给 casper.evaluate
。 evaluate()
基本上是在调用 phantomjs 的 evaluate()
,所以他们的 docs 很有帮助:
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.
所以你有点卡住了,需要找到不同的方法来做到这一点。
我有波纹管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);
}
});
});
};
};
当我尝试调用 x() 时,出现此错误:ReferenceError: Can't find variable: x
.
但是 x 是我可以从任何嵌套函数访问的全局变量。对吗?
谢谢
x
不是全局变量,它是 casperInstance
函数的局部变量。我建议
this.casper.selectXPath('//*[@id="email_address"]');
这是使用 Casper
.
通常,javascript 函数会在闭包中捕获 x
,并且它可用于范围内的函数。这就是这里应该发生的事情。但问题是 casper.evaluate()
专门避免了这一点 -- evaluate()
的要点是使用当前页面 DOM 的上下文。这意味着您只能访问页面的范围。文档在这一点上实际上非常好:
http://docs.casperjs.org/en/latest/modules/casper.html#evaluate
您将无法将函数传递给 casper.evaluate
。 evaluate()
基本上是在调用 phantomjs 的 evaluate()
,所以他们的 docs 很有帮助:
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.
所以你有点卡住了,需要找到不同的方法来做到这一点。