은 대략 말하기 :
var Confirm = (function()
function Confirm(element, message) {
var self = this;
this.message = message;
hookEvent(element, "click", function(event) {
self.doConfirm(event);
});
}
Confirm.prototype.doConfirm = Confirm$doConfirm;
function Confirm$doConfirm(e) {
if (!confirm(this.message)) {
if (e.stopPropagation) {
e.stopPropagation();
}
else {
e.cancelBubble = true;
}
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
}
}
return Confirm;
})();
가 (. 당신은 익명 함수를 사용하여 괜찮다면 약간이 단축 될 수 있습니다, 나는 기능 이름을 부여하여
help my tools help me 선호)
위의 경우 hookEvent
은 addEventListener
또는 attachEvent
(IE8 이하를 지원하기 위해)을 다음과 같이 호출해야하는 유틸리티 함수입니다.
function hookEvent(element, eventName, handler) {
// Very quick-and-dirty, recommend using a proper library,
// this is just for the purposes of the example.
if (typeof element.addEventListener !== "undefined") {
element.addEventListener(eventName, handler, false);
}
else if (typeof element.attachEvent !== "undefined") {
element.attachEvent("on" + eventName, function(event) {
return handler(event || window.event);
});
}
else {
throw "Browser not supported.";
}
}
브라우저 간 호환성을 위해 얼마나 많은 작업이 필요한지 유의하십시오. Prototype을 사용할 필요는 없지만 Prototype이 아니더라도 다른 괜찮은 라이브러리 (예 : jQuery, YUI, Closure 또는 any of several others)를 사용하는 것이 좋습니다. 로트을 저장하여 브라우저 간 차이점을 해결하고이 분야의 다른 사람들이 수행 한 중요한 작업을 활용하여 발생하는 엣지 케이스를 처리합니다.
var Confirm = (function()
function Confirm(element, message) {
this.message = message;
$(element).click($.proxy(this.doConfirm, this));
}
Confirm.prototype.doConfirm = Confirm$doConfirm;
function Confirm$doConfirm(e) {
if (!confirm(this.message)) {
return false;
}
}
return Confirm;
})();
여전히 (명시 적 폐쇄를 만들지 않도록하는 hookEvent
에 대한 $().click
, $.proxy
를 사용 : 당신의 목표는 전체 라이브러리를 이동보다는 프로토 타입을 이동하는 경우
, 여기에 예를 들어 jQuery를 사용하여 그 같은 일이다 jQuery 이벤트 핸들러에서 return false
은 Propagation의 stop
처럼 전파를 중지하고 기본 액션을 방지하는 것과 동일하다는 사실을 알고 있어야합니다. 브라우저의 차이에 대해 걱정하지 않고 stopPropagation
및 preventDefault
을 사용할 수도 있습니다. jQuery가 그것을 처리한다. 대부분의 도서관은
Prototype에서 벗어 났지만 Class
기능과 비슷한 것을 원한다면 here's one 코드에 넣을 수 있습니다. 그 블로그 게시물의 내 목표는 Prototype의 Class
(프로토 타입을 사용하고있을 당시)을 대체하는 것이 아니라 Prototype의 이라는 엄밀히 말하면 수정 한 것입니다. 비효율적 인 방법으로 수퍼 콜을 처리합니다. 그러나 그렇게함으로써, Class
을 대신 할 수있는 완전한 구현이 생성되었습니다. 물론 클래스에 관한 용어가 아니기 때문에 (자바 스크립트에는 클래스가 없다) 자바 스크립트의 프로토 타입 상속에 대한 유용한 설교가 필요하기 때문에 용어를 업데이트해야한다.
프로토 타입 자바 스크립트입니다. – Jeff
@FelixKling. 이것은 내가 제일 좋아하는 술집에서 처음으로 간다. –