2012-02-18 13 views
1

私は.prototypeと思われるものを誤解していますか、これはちょうどうまくいきませんか?javascriptプロトタイプが動作しない

window.dump = function() { 
    for (var i = 0, x = dump.list.length; i < x; ++i) console.log.apply(this, dump.list[i]); 
    if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) dump.purge(); 
} 
dump.prototype = { 
    list : [], 
    log : function() { 
     dump.list.push(arguments); 
    }, 
    purge : function() { 
     dump.list = []; 
    } 
} 
dump.log('test1'); 
dump.log('test2'); 
dump(); 

私の代わりにdump.logが定義されていない、 "TEST1" と "TEST2は" console.logを通過することを期待しています。ただし、dump.prototype.logです。

編集:私は以下を試してみました。このプロトタイプを正しいものにすることはできません。

window.dump = new function() { 
    this.list = []; 
    this.log = function() { 
     this.list.push(arguments); 
    } 
    this.purge = function() { 
     return this.list = []; 
    } 
    return function() { 
     for (var i = 0, x = this.list.length; i < x; ++i) console.log.apply(this, this.list[i]); 
     if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) this.purge(); 
    } 
} 

次のように私のコードを使用できる正しい方法は何ですか?

dump.log('test1'); 
dump.log('test2'); 
dump(); 

編集:最終的な結果はMatthew Flaschenのおかげです。

(function() { 
    var console_log = Function.prototype.bind.call(console.log, console); 
    window.dump = function() { 
     for (var i = 0, x = dump.list.length; i < x; ++i) console_log.apply(this, dump.list[i]); 
     if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) dump.purge(); 
    }; 
    dump.list = []; 
    dump.log = function() { 
     dump.list.push(arguments); 
    } 
    dump.purge = function() { 
     dump.list = []; 
    } 
})(); 

私は明らかにconsoleは、標準的なオブジェクトではありませんので、console.logをラップするconsole_logを割り当てるために持っていました。したがって、applyメソッドの標準Functionオブジェクトではありません。私が実際にGoogleを使っている証拠。

答えて

6

はい、正しいバージョンは以下のとおりです。 dumperはコンストラクタ関数です。したがって、listメンバを初期化します。

以下、希望する方法でdumperプロトタイプを設定します。これらはthisも使用できます。 dumperのインスタンス(dなど)には、これらのメソッドがあります。

window.dumper = function() { 
    this.list = []; 
}; 

dumper.prototype = { 

    log : function() { 
     this.list.push(arguments); 
    }, 
    purge : function() { 
     this.list = []; 
    }, 
    dump : function() { 
     for (var i = 0, x = this.list.length; i < x; ++i) console.log.apply(this, this.list[i]); 
     if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) this.purge(); 
    } 
} 


var d = new dumper();   

d.log('test1'); 
d.log('test2'); 
d.dump(); 
+0

+1あなたは私にそれを打つ! – maerics

+0

ダンプ機能として実際に "d"を使用する方法はありませんか? – Shea

+0

@andrewjackson、もしあなたが 'dump'をシングルトンにしたとします。しかし、それは 'prototype'を使うことの全ポイントを打ち破ってしまいます。あなたがしなければJavaScriptオブジェクトモデルと戦おうとしないでください。 –

関連する問題