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

时间:2016-06-28 21:23:37

标签: 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以及其他调试信息。第二个不起作用,什么都不输出,它有什么问题?

1 个答案:

答案 0 :(得分:1)

It's all about context.

在您的情况下,this指的是window.object,可能不是您所期望的。原生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。 ;)