javascript - casperjs:显示调试信息输出的正确方法

标签 javascript scope casperjs

var casper = require('casper').create({
  logLevel:'debug',
  verbose:true
});

casper.start('http://pcdtattoo.en.alibaba.com/productlist.html',function getItems(){
  var products = this.evaluate(function(){
    var $ = jQuery;
    var c = $('.app-productsGalleryView li');
    var items = [];
    c.each(function(){
      var product = {};
      product.title = $(this).find('.product-title>a').text().trim();
      product.link = $(this).find('.product-title>a').attr('href');
      product.img = $(this).find('img').attr('src');
      items.push(product);
    })
    return items;
  })
  this.echo("test:"+ Array.isArray(products));    //works
  products.forEach(function(item,i){
    this.echo('Test:' + i);                      //not working
  })
}

我通常使用 this.echo 将调试信息显示到输出中。在上面的代码中,第一个 this.echo 调用起作用,并将输出 test:true 以及其他调试信息。第二个不起作用并且没有输出任何内容,这是怎么回事?

最佳答案

It's all about context.

在您的情况下,this 指的是window.object,并且可能不是您所期望的。 native forEach 接受第二个参数 (arr.forEach(callback[, thisArg])),它允许您传递上下文。

示例

[1,2,3].forEach(function () {
    console.log(this); //  this refers to window
});

// output
[object DOMWindow]
[object DOMWindow]
[object DOMWindow]


[1,2,3].forEach(function () {
    console.log(this); //  this refers to caspar
}, this);

// output
[object Casper], currently at https://localhost/de/register
[object Casper], currently at https://localhost/de/register
[object Casper], currently at https://localhost/de/register

提示: It's always good to know your API 。 ;)

关于javascript - casperjs:显示调试信息输出的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086545/

相关文章:

Ruby 变量作用域

xpath - 如何使用 CasperJS 和 PhantomJS 从表中抓取数据

node.js - casperjs中的waitforSelector函数

javascript - 单击鼠标添加声音

javascript - 如何检查 Canvas 框架

javascript - 将 JSP Java 代码添加到 HTML 中的占位符属性

javascript - jquery 文件内部或外部的函数就绪

python - 主函数python中的全局变量

javascript - 通过企业代理的 HTTP 407 CasperJS

javascript - Canvas toDataUrl 的跨源访问失败