如何扩展Javascript Date对象? [英] How to extend the Javascript Date object?

查看:110
本文介绍了如何扩展Javascript Date对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试过这个:

$ b我试图子类化/扩展本地Date对象,而不修改本机对象本身。
$ b

  var util = require('util'); 

函数MyDate(){
Date.call(this);
}
util.inherits(MyDate,Date);

MyDate.prototype.doSomething = function(){
console.log('Doing something ...');
};

var date = new MyDate();
date.doSomething();

console.log(date);
console.log(date.getHours());

而这个:

 函数MyDate(){

}

MyDate.prototype = new Date();

MyDate.prototype.doSomething = function(){
console.log(DO);
}

var date = new MyDate();
date.doSomething();
console.log(date);

在这两种情况下, date.doSomething()工作,但是当我调用任何本机方法,如 date.getHours()甚至 console.log(date),我得到'TypeError:这不是一个Date对象'。



任何想法?或者我坚持扩展顶级Date对象?

解决方案

查看v8代码,在date.js中: / p>

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

看起来像DATE_VALUE是一个这样做的宏:

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

所以,似乎v8不会让你子类Date。


I'm trying to subclass/extend the native Date object, without modifying the native object itself.

I've tried this:

    var util = require('util');

    function MyDate() {
        Date.call(this);
    }
    util.inherits(MyDate, Date);

    MyDate.prototype.doSomething = function() {
        console.log('Doing something...');
    };        

    var date = new MyDate();
    date.doSomething();

    console.log(date);
    console.log(date.getHours());

and this:

function MyDate() {

    }

    MyDate.prototype = new Date();

    MyDate.prototype.doSomething = function() {
        console.log("DO");
    }

    var date = new MyDate();
    date.doSomething();
    console.log(date);

In both cases, the date.doSomething() works, but when I call any of the native methods such as date.getHours() or even console.log(date), I get 'TypeError: this is not a Date object.'

Any ideas? Or am I stuck to extending the top-level Date object?

解决方案

Looking at the v8 code, in date.js:

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

And looks like DATE_VALUE is a macro that does this:

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

So, seems like v8 won't let you subclass Date.

这篇关于如何扩展Javascript Date对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆