JavaScript对象不是从原型链继承的

时间:2012-09-08 18:46:29

标签: javascript prototypejs prototype

我在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;

直观地说,在我看来我应该能够这样做(因为在Root构造函数中定义了subclass()):

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,而子类()也按预期在这些对象上执行。

我从中得到的是,CurrentDate构造函数被排除在CurrentDate:CustomDateTime:Root链之外,只是被称为独立构造函数 - 使用此函数创建的对象似乎不是继承自分配给CurrentDate函数对象的原型。

这不是使用JavaScript原型的正确方法吗?同样,在我看来,这应该会非常顺利..

1 个答案:

答案 0 :(得分:0)

感谢'灰色状态即将到来'的回应。看到j​​sfiddle中正确运行的代码告诉我,当你在.html页面上包含多个标签时,你必须按照原型继承的顺序放置标签。如果CurrentDate在CustomDateTime之前,则在分配CurrentDate.prototype时尚未定义CustomDateTime函数。

相关问题