2013-05-17 4 views
0

다음 코드 jsFiddle을 사용하여 양식 필드 및 이벤트 작업을하고 있습니다. 나는 이전에이 문제에 관해서 두 가지 질문을했고 그들은 나를 대단히 도왔다. 이제 새로운 문제/질문이 있습니다. 이벤트 처리를위한 부모 프로토 타입 메서드 재정의

function Field(args) { 
    this.id = args.id; 

    this.elem = document.getElementById(this.id); 
    this.value = this.elem.value; 
} 

Field.prototype.addEvent = function (type) { 
    this.elem.addEventListener(type, this, false); 
}; 

// FormTitle is the specific field like a text field. There could be many of them. 
function FormTitle(args) { 
    Field.call(this, args); 
} 

Field.prototype.blur = function (value) { 
    alert("Field blur"); 
}; 

FormTitle.prototype.blur = function() { 
    alert("FormTitle Blur"); 
}; 

Field.prototype.handleEvent = function(event) { 
    var prop = event.type; 
    if ((prop in this) && typeof this[prop] == "function") 
     this[prop](this.value); 
}; 

inheritPrototype(FormTitle, Field); 
var title = new FormTitle({name: "sa", id: "title"}); 
title.addEvent('blur'); 


function inheritPrototype(e, t) { 
    var n = Object.create(t.prototype); 
    n.constructor = e; 
    e.prototype = n 
} 

if (!Object.create) { 
    Object.create = function (e) { 
     function t() {} 
     if (arguments.length > 1) { 
      throw new Error("Object.create implementation only accepts the first parameter.") 
     } 
     t.prototype = e; 
     return new t 
    } 
} 

문제

내가 부모 방법 (Field.prototype.blur)을 무시하고 대신 제목 개체에 대한 FormTitle.prototype.blur 방법을 사용할 것입니다. 그러나 개체는 부모 메서드를 계속 참조하며 경고는 항상 'FormTitle Blur'대신 'Field blur'를 표시합니다. 이 작품을 어떻게 만들 수 있습니까?

답변

1

FormTitle 프로토 타입에 메서드를 정의한 다음 inheritPrototype을 사용하여 전체 프로토 타입을 다른 개체로 바꿉니다.

주문을 교환해야합니다. 먼저이 전화 :

FormTitle.prototype.blur = function() { 
    alert("FormTitle Blur"); 
}; 

http://jsfiddle.net/zMF5e/2/

+0

아하 :

inheritPrototype(FormTitle, Field); 

그런 다음 방금 만든 프로토 타입 객체에 위해 onblur 설정! 그것은 의미가 있습니다. 그건 그렇고, 프로토 타입 상속 이벤트/양식 필드 처리에 대한 좋은 일치인가? 아니면 완전히 잘못하고있는 것입니까? – user

+1

사실 전혀 코딩 스타일이 마음에 들지 않습니다. addEventListener 및 handleEvent는 IE8 이하에서는 작동하지 않습니다. – bfavaretto

+0

감사합니다. 그렇습니다. MDN의 호환성 코드를 추가했습니다. – user

관련 문제