1. 调试工具

firebug

FireBug

1.1. 控制台输出

调试Javascript,不必再加入很多的alert了,用Firebug提供的console会方便很多

console.log('width: %d height: %d', width, height);

就会在Firebug控制台显示出数据

200605120356

当然也可以直接打印对象

var myArray = ['item1', 'item2', 'item3'];
console.log(myArray);

200605120414

还支持log级别,方便标识不同的情况

console.debug('I am debug');
console.info('I am info');
console.warn('I am a warning');
console.error('I am an error');

200605120440

1.2. 计算代码运行时间

有时我们为了看到代码的运行效率,经常要加入计算时间的代码,现在可以直接加入了,在要计算的代码前后分别加入如下代码:

console.time(key);
console.timeEnd(key);

详细例子:

  importImages: function() {
    console.time('Loading Images');
    this.options.images.collect(function(image) {
      var img = new Image();
      img.src = this.options.filePath + image;
      console.time('event binding');
      Event.observe(img, 'load', this.onImageLoaded.bind(this, img));
      console.timeEnd('event binding');
      return img;
    }.bind(this));
    console.timeEnd('Loading Images');
  },

200605120448

1.3. Trace Execution

看看哪些地方引用了某个函数,很方便,对于接手的代码,可能会改动某一个函数而影响很多地方,为了做到心中有数,可以在函数的最后执行console.trace();控制台就会打印出哪些文件引用了该函数。

例子:

importImages: function() {
    this.options.images.collect(function(image) {
      var img = new Image();
      img.src = this.options.filePath + image;
      Event.observe(img, 'load', this.onImageLoaded.bind(this, img));
      return img;
    }.bind(this));
    console.trace();
  },

200605120503

1.4. 断点

切换到debugger窗口,可以看到当前页相关的js和html代码,在行首双击就可以加入断点

firebug-debug-console-1-tm

然后可以随时在console窗口监视变量的值

200605120612

1.5. 查看动态DOM

切换到Inspector窗口,点击Inspect,然后就可以看到页面任意部分的html代码了,注意,这里看到的html源码,也包含通过js动态生成的html部分,这个特性非常方便,可以很容易的看到最终的渲染结果是否正确。

1

1.5.1. Firebug推荐资料

1.An In-depth Look At The Future of Javascript Debugging With Firebug

2.FireBug Documentation