.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();
나는 "TEST1"와 "TEST2는"대신 dump.log
가 정의되어 있지 않은, 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에게 감사합니다. 분명히 console
표준 객체가 아니기 때문에
(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.log
을 래핑하는 console_log
을 할당 했어. 따라서 apply
메서드를 사용하는 표준 Function
개체는 아닙니다. 내가 실제로 사용하는 증거는 Google을 사용합니다.
+1 당신이 저를 때려 눕히십시오! – maerics
"d"를 덤프 함수로 실제로 사용할 수있는 방법이 없습니까? – Shea
@andrewjackson, 아마'dump'를 싱글 톤으로 만들면됩니다. 그러나 그것은 프로토 타입을 사용하는 모든 점을 무너 뜨린다. 당신이해야하지 않는 한 JavaScript 객체 모델과 싸우려고 시도하지 마십시오. –