はじめに
JavaScriptはいい言語だけど、コンソール出力が標準で備わっていないことがプログラマに嫌われる理由の一つだと思う(標準に組み込んで欲しいなあ)。console.log()はほとんどの環境で入っているけどオブジェクトのデバッグ表示が貧弱なのが痛い。
var obj = {a:1, b:2, c:3}; console.log(obj); => [object Object] // oh...
ってなる、知りたいのはその奥なのだ。
Firebugではconsole.dir()という関数が用意されていて、オブジェクトの中身を表示することが出来る。残念ながらAdd-on SDKではconsole.log()しか用意されていないので自作することにした。
サンプルコード
基本。
console.dir({a: 1, b: 2, c: 3}); => info: a: 1 b: 2 c: 3
おまけで文字列出力も。
console.dir_s({a: 1, b: 2, c: 3}); => "info:\n a: 1\n b: 2\n c: 3"
関数のみで構成されたオブジェクト。
console.dir({f1: function() {}, f2: function() {}, f3: function() {}}, "Disp functions."); => info: Disp functions. f1() f2() f3()
関数とプロパティの組み合わせ。
console.dir({f1: function() {}, a : 1, b : 2, funcs: function() {}}, "property & function"); => info: property & function property: a: 1 b: 2 function: f1() funcs()
Add-on SDK標準のオブジェクトもこの通り。
const panel = require('panel'); console.dir(panel.Panel({ width: 800, height: 800, contentURL: data.url('index.html'), contentScriptFile: [data.url('game.js')], contentScriptWhen: 'ready' })); => info: property: allow: [object Object] contentScript: null contentScriptFile: resource://jid1-ckmgqls2uqipog-enchant-test-data/game.js contentScriptWhen: "ready" contentURL: "resource://jid1-ckmgqls2uqipog-enchant-test-data/index.html" height: 800 isShowing: false port: [object Trait] width: 800 function: destroy() hide() on() once() postMessage() removeListener() resize() show()
使い方
- console-dir.jsをダウンロード
- 自分のアドオン/lib/console-dir.js に置く
- 使いたい箇所で require("console-dir") すれば OK
require("console-dir"); . . . export.foo = function() { console.dir(obj); }
まとめ
- 気が向いたら本家にpull requestしてみようかな
- 最終的には console.p() が作りたい
- 要望、感想等ありましたらどうぞ