私は.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を使っている証拠。
+1あなたは私にそれを打つ! – maerics
ダンプ機能として実際に "d"を使用する方法はありませんか? – Shea
@andrewjackson、もしあなたが 'dump'をシングルトンにしたとします。しかし、それは 'prototype'を使うことの全ポイントを打ち破ってしまいます。あなたがしなければJavaScriptオブジェクトモデルと戦おうとしないでください。 –