javascript method called on incompatible Object
PHPz
PHPz 2017-04-10 14:45:36
[JavaScript讨论组]
    '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.

PHPz
PHPz

学习是最好的投资!

全部回复(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的原型链上扩展。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号