JavaScript インスタンス変数の初期化

実行結果



スクリプトコード

var foo = {};
foo.Bar = function() {
    this.prop1_ = 4;
    this.prop2_ = true;
    this.prop3_ = [];
    this.prop4_ = 'blah';
};

var hoge = {};
hoge.Bar = function() {
    this.prop3_ = [];
};
hoge.Bar.prototype.prop1_ = 4;
hoge.Bar.prototype.prop2_ = true;
hoge.Bar.prototype.prop4_ = 'blah';

$(function() {
    $('#run').click(function() {
        var f = new foo.Bar();
        var h = new hoge.Bar();
        $('#debug').html(
            "f.toSource() => " + f.toSource() + "\n" +
            "h.toSource() => " + h.toSource() + "\n" +
            "f.prop1 => " + f.prop1_ + "\n" +
            "h.prop1 => " + h.prop1_ + "\n" +
            "f.prop2 => " + f.prop2_ + "\n" +
            "h.prop2 => " + h.prop2_ + "\n" +
            "f.prop3 => " + f.prop3_.toSource() + "\n" +
            "h.prop3 => " + h.prop3_.toSource() + "\n" +
            "f.prop4 => " + f.prop4_ + "\n" +
            "h.prop4 => " + h.prop4_
        );
    });
});

参考:JavaScriptの最適化について、code.google.comの記事の適当訳 - それ図解で。・・・tohokuaikiのチラシの裏
   Let's make the web faster - Google Code