【问题标题】:Object doesn't support this property or method (custom prototype method of custom object)对象不支持此属性或方法(自定义对象的自定义原型方法)
【发布时间】:2015-04-28 16:52:26
【问题描述】:

我有这个代码:

function Event(fromDate, toDate, color) {
    if (toDate < fromDate) {
        throw "Invalid date interval";
    }
    this.fromDate = fromDate;
    this.toDate = toDate;
    this.color = color;
}

Event.prototype._compareDates = function (date1, date2) {
    if (date1 && date2) {
        return date1.getTime() - date2.getTime();
    } else {
        return null;
    }
};

Event.prototype.inInterval = function (date) {
    return (this._compareDates(date, this.fromDate) >= 0) && (this._compareDates(date, this.toDate) <= 0);
};

Event.prototype.isCoveredBy = function (event) {
    return (this._compareDates(event.fromDate, this.fromDate) < 0) && (this._compareDates(event.toDate, this.toDate) > 0);
};

Event.prototype.overlapsWith = function (event) {
    return this.inInterval(event.fromDate) || this.inInterval(event.toDate) || this.isCoveredBy(event);
};

var event1 = new Event(new Date(), new Date(), "#ffffff");
var event2 = new Event(new Date(), new Date(), "#ffffff");

alert(event1.overlapsWith(event2));

它适用于 Chrome 和 Firefox,但在 Internet Explorer 11 上似乎找不到任何 Event.prototype.foo 函数并抛出错误“对象不支持此属性或方法 'foo'。

更新:

问题在于这段代码:

function saveOrUpdate(color) {
    var fromDate = PF('fromDate').getDate();
    var toDate = PF('toDate').getDate();
    event = new Event(fromDate, toDate, color);
    $('#inlineDatepicker').datepick('addOrUpdateEvent', event);
    $('#inlineDatepicker').datepick('clear');
}

使用 PrimeFaces RequestContext 从 bean 调用它以将新事件添加到 Javascript 日历。请注意,第三行并没有像我预期的那样声明一个新变量“事件”。

出于某种原因,IE11 将事件解释为全局命名空间中的 Event 类型(请参阅 Andrei Nemes 答案),而不是我自己的同名自定义类型。 Chorme 和 Firefox 正确解释类型。因此,解决方案是更改第三行,添加“var”:

var event = new Event(fromDate, toDate, color);

很抱歉之前没有发布这部分代码。我将更改我的 Event 类的名称以避免将来出现问题。

【问题讨论】:

  • 简要看一下您的代码,我没有看到任何真正称为“foo”的东西......是否缺少任何代码?通常,如果您使用调试工具,如果单击错误,则会转到一行。你知道它要去哪条线吗?
  • @DylanCorriveau 据我所知,looks like it cannot find **any** of the Event.prototype.foo functions 并不意味着他试图访问 foo()。也就是说,他实际定义的四个函数,一个都找不到。
  • 是的,我指的是每个 Event.propotype 函数,例如“overlapsWith”或“inInterval”。

标签: javascript internet-explorer-11


【解决方案1】:

Event 已存在于全局命名空间中。当您声明 Event.prototype.overlapsWith 时,Internet Explorer 会将其附加到本机 Event 对象而不是您的类声明。如果您查看Event 对象,您可以在那里看到它。 简单的解决方法是不使用名称Event

编辑:没关系,它似乎有效。不过,使用 Event 这个名称可能仍然不是一个好主意。您能否添加有关该错误的更多详细信息?

【讨论】:

  • 不,本地类声明应该隐藏全局 Event 构造函数。