【问题标题】:Overriding parent prototype method for event handling覆盖事件处理的父原型方法
【发布时间】:2013-05-17 22:27:56
【问题描述】:

我正在使用以下代码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 方法。但是该对象一直引用父方法,并且警报始终显示“字段模糊”而不是“表单标题模糊”。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript events javascript-events event-handling


    【解决方案1】:

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

    您必须交换订单。首先你称之为:

    inheritPrototype(FormTitle, Field);
    

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

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

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

    【讨论】:

    • 啊哈!这很有意义。顺便说一句,原型继承是否适合事件/表单字段处理?还是我完全做错了?
    • 一点都没有错,其实我喜欢这种编码风格。请记住 addEventListener 和 handleEvent 在 IE8 及以下版本中不起作用。
    • 非常感谢,是的,我添加了 MDN 的兼容性代码来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 2011-04-17
    相关资源
    最近更新 更多