重写用于事件处理的父原型方法
Overriding parent prototype method for event handling
我使用以下代码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/相关文章:
- 使用“;这个“;JavaScript原型方法中的关键字
- 引用类变量中的原型方法
- 如何从对象的原型方法访问JavaScript对象属性
- 如何从构造函数中调用js原型方法
- Javascript不调用原型方法
- 有没有任何情况下,一个方法不应该是原型方法
- 调用影子原型方法的更简单/更好的方法
- 当对象从服务器发送到客户端时,JS原型方法消失了
- 构造 JavaScript Array 原型方法
- 在Javascript中扩展继承的原型方法
- 如何在另一个原型中创建可调用的原型方法
- 覆盖原型方法
- 实现原型方法
- 从原型方法更改实例属性
- XrayWrapper 错误(值是可调用的)在 Firefox 插件中覆盖原型方法时
- 避免在外部称为原型方法中丢失对象实例
- 原型方法不是一个函数,为什么
- 是否可以从 javascript 中的原型方法访问私有类属性
- 找不到 Javascript 原型方法覆盖
- 调用本机原型方法时扩展或继承对象原型