2012-02-18 4 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(); 

나는 "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을 사용합니다.

답변

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'를 싱글 톤으로 만들면됩니다. 그러나 그것은 프로토 타입을 사용하는 모든 점을 무너 뜨린다. 당신이해야하지 않는 한 JavaScript 객체 모델과 싸우려고 시도하지 마십시오. –

관련 문제