【发布时间】:2012-09-08 18:46:28
【问题描述】:
我在 Chrome 21 中为我的构造函数定义原型时遇到了麻烦。我正在做一个大项目,在该项目中我试图实现一个基于伪类的结构(因此是“子类”属性)一些非常松散的数据封装,但我对 JavaScript 中的原型设计和继承相对较新,无法弄清楚出了什么问题。 StackOverflow 上还有其他类似的线程,但没有解决这个问题。
这是我正在使用的构造函数:
function Root()
{
this._subclass = "Root";
this.subclass = function(){
return this._subclass;
};
this._date;
this.date = function(){
return this._date;
};
}
function CustomDateTime()
{
this._subclass = "CustomDateTime";
this._value = new Date();
}
CustomDateTime.prototype = new Root;
function CurrentDate()
{
this._subclass = "CurrentDate";
}
CurrentDate.prototype = new CustomDateTime;
直觉上,在我看来我应该能够做到这一点(因为 subclass() 是在 Root 构造函数中定义的):
var now = new CurrentDate();
alert(now.subclass()); // should alert "CurrentDate"
但是在运行脚本时我得到了一个TypeError: Object #<CurrentDate> has no method 'subclass'。此外,如果我更改 CurrentDate 构造函数以包含此警报:
function CurrentDate()
{
alert(this._subclass);
this._subclass = "CurrentDate";
}
CurrentDate.prototype = new CustomDateTime;
结果消息是undefined。
如果我指定var now = new CustomDateTime(),则调用 subclass() 方法会按预期返回“CustomDateTime”。我还定义了另一个构造函数ModelObject,其原型设置为Root,并且 subclass() 也可以在这些对象上按预期执行。
我从中得到的是 CurrentDate 构造函数被排除在 CurrentDate 之外: CustomDateTime :根链并且只是被称为独立构造函数 - 使用此函数创建的对象似乎没有继承自分配给 CurrentDate 函数对象的原型。
这不是使用 JavaScript 原型的正确方法吗?再一次,在我看来,这应该非常顺利..
【问题讨论】:
-
您的第一个代码示例
alert(now.subclass());工作正常。没有“没有方法”错误。 jsfiddle.net/WL5tC
标签: javascript prototypejs prototype