【问题标题】:How to access globar variable with nested functions ? javascript如何使用嵌套函数访问全局变量? javascript
【发布时间】:2017-09-17 03:03:37
【问题描述】:

我有下面的课程:

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 是全局变量,我可以从任何嵌套函数访问。对吧?

谢谢

【问题讨论】:

  • 尝试 window.x 并检查拼写和大写字母
  • 为了获得更好的答案,您可以提供一个最小问题和预期行为的小提琴

标签: javascript global-variables javascript-objects nested-function


【解决方案1】:

这是使用 Casper 之类的东西时的常见问题。

通常,javascript 函数会在闭包中捕获x,并且该范围内的函数可以使用它。这就是它看起来应该在这里发生的事情。但问题是casper.evaluate() 专门避免了这一点——evaluate() 的重点是使用当前页面 DOM 的上下文。这意味着您只能访问页面的范围。在这一点上,文档实际上非常好:

http://docs.casperjs.org/en/latest/modules/casper.html#evaluate

您无法将函数传递给casper.evaluateevaluate() 基本上是在调用phantomjs 的evaluate(),所以他们的docs 很有帮助:

注意:评估函数的参数和返回值必须是简单的原始对象。经验法则:如果可以通过 JSON 序列化就可以了。

所以你有点卡住了,需要找到一种不同的方法来做到这一点。

【讨论】:

    【解决方案2】:

    x 不是全局变量,它是casperInstance 函数的局部变量。我建议

    this.casper.selectXPath('//*[@id="email_address"]');
    

    【讨论】:

    • 感谢您的回答,但它不起作用,我收到此错误:TypeError: undefined is not an object (evalating 'this.casper.selectXPath')
    猜你喜欢
    • 2020-06-12
    • 2019-11-21
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多