重写用于事件处理的父原型方法

Overriding parent prototype method for event handling

本文关键字:原型 方法 用于 事件处理 重写      更新时间:2023-09-26

我使用以下代码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方法的标题对象。但是对象一直引用父方法并且警告总是显示'Field blur'而不是'FormTitle blur'。我该怎么做呢?

您正在FormTitle原型中定义一个方法,然后使用inheritPrototype将整个原型替换为另一个对象。

你必须交换顺序。首先调用这个:

inheritPrototype(FormTitle, Field);

然后在刚刚创建的原型对象上设置onblur:

FormTitle.prototype.blur = function () {
    alert("FormTitle Blur");
};
http://jsfiddle.net/zMF5e/2/