javascript method called on incompatible Object

    'use strict';
    function inheritPrototype(subType,superType) {
        var prototype=Object(superType.prototype);
        prototype.constructor=subType;
        subType.prototype=prototype;
    }
    function SubType() {
        Date.call(this);
    }
    inheritPrototype(SubType,Date);
    var child=new SubType();
    alert(child.getFullYear());

之所以要继承Date类型,是因为我想写一个子类型,提供中文日期的格式化功能,但是却遇到了如下问题
图片描述
图片描述
这是为什么呢?我用child instanceOf Date测试过,得到的结果是true,但是为啥还会出现这类问题呢?

我看到github上有人提到了ECMAScript 5 规范中提到的date类型的部分,然后我看了一下,现在把他贴过来,谁能帮我翻译一下下面这段英文的解释是啥意思吗?

15.9.5 Properties of the Date Prototype Object

The Date prototype object is itself a Date object (its [[Class]] is "Date") whose [[PrimitiveValue]] is NaN.

The value of the [[Prototype]] internal property of the Date prototype object is the standard built-in Object prototype object (15.2.4).

In following descriptions of functions that are properties of the Date prototype object, the phrase “this Date object” refers to the object that is the this value for the invocation of the function. Unless explicitly noted otherwise, none of these functions are generic; a TypeError exception is thrown if the this value is not an object for which the value of the [[Class]] internal property is "Date". Also, the phrase “this time value” refers to the Number value for the time represented by this Date object, that is, the value of the [[PrimitiveValue]] internal property of this Date object.

回复
阅读 4k
1 个回答

把@Larvata的评论里地址答案稍微解释下。

看看v8的date.js文件:

function DateGetHours() {
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
  return HOUR_FROM_TIME(LocalTimeNoCheck(t));
}

然后看看DATE_VALUE这个宏指令

DATE_VALUE(arg) = (%_ClassOf(arg) === 'Date' ? %_ValueOf(arg) : ThrowDateTypeError());

意思就是不让继承。

对于你这样需求,我们一般就是直接在Date的原型链上扩展。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏