Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Subclassing Date weirdness.

0 views
Skip to first unread message

nick

unread,
Apr 18, 2010, 3:52:49 PM4/18/10
to
I decided to I wanted to subclass the native Date object, but realized
that you can't call Date.prototype's function properties with anything
but a 'pure' date object as the execution context. So, I decided to
wrap all of Date.prototype's important functions, which worked out
pretty well...

The weirdness comes into play with the toString and valueOf methods.
In particular, my MyDate class gives different values for (''+new
MyDate) and (new MyDate.toString()), which confuses me. I didn't
expect the results to differ from (''+new Date) and (new
Date.toString()).

Here's some example code to reproduce it...

/** datetest.js */

// MyDate constructor
var MyDate = function () {
this._date = new Date();
}

// MyDate class definition
MyDate.prototype = (function(){

// for instanceof
var Clone = new Function;
Clone.prototype = Date.prototype;
var base = new Clone;

// native methods of Date.prototype
var _nm = ['getDate','getDay','getFullYear','getHours',
'getMilliseconds','getMinutes','getMonth','getSeconds',
'getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds',
'getUTCMinutes','getUTCMonth','getUTCSeconds','getYear',
'setDate','setFullYear','setHours','setMilliseconds',
'setMinutes','setMonth','setSeconds','setTime',
'setUTCDate','setUTCFullYear','setUTCHours',
'setUTCMilliseconds','setUTCMinutes','setUTCMonth',
'setUTCSeconds','setYear','toDateString','toGMTString',
'toISOString','toJSON','toLocaleDateString',
'toLocaleString','toLocaleTimeString','toString',
'toTimeString','toUTCString','valueOf'];

// create wrappers for native methods
for (var i=_nm.length; i--;) (function (f) {
base[f] = function() {
return Date.prototype[f].apply(this._date, arguments);
}
})(_nm[i]);

// our class prototype
return base;

})();

// testing it out

var c = console;

c.log("======== Date ========");
c.log("new Date() : ", new Date());
c.log("''+new Date() : ", ''+new Date());
c.log("(new Date()).toString() : ", (new Date()).toString());
c.log("(new Date()).valueOf() : ", (new Date()).valueOf());

c.log("======== MyDate ========");
c.log("new MyDate() : ", new MyDate());
c.log("''+new MyDate() : ", ''+new MyDate());
c.log("(new MyDate()).toString() : ", (new MyDate()).toString());
c.log("(new MyDate()).valueOf() : ", (new MyDate()).valueOf());

/// EOF

Anyone have any idea what's going on here?

-- Nick

Asen Bozhilov

unread,
Apr 18, 2010, 5:30:40 PM4/18/10
to
nick wrote:

> I decided to I wanted to subclass the native Date object, but realized
> that you can't call Date.prototype's function properties with anything
> but a 'pure' date object as the execution context. So, I decided to
> wrap all of Date.prototype's important functions, which worked out
> pretty well...

That design is not really good decision. It is memory inefficient and
break forward compatible with non generics methods for Date
instances.

> The weirdness comes into play with the toString and valueOf methods.
> In particular, my MyDate class gives different values for (''+new
> MyDate) and (new MyDate.toString()), which confuses me. I didn't
> expect the results to differ from  (''+new Date) and (new
> Date.toString()).

By specification that is normal behavior, because Date instances have
special [[DefaultValue]]. During evaluation of addition expression,
objects will be converted to primitive value. For type converting will
be use internal [[DefaultValue]] of that object, without passing hint
argument.

| ECMA-262-3
| 8.6.2.6 [[DefaultValue]] (hint)
| When the [[DefaultValue]] method of O is called with no hint,
| then it behaves as if the hint were Number, unless O is
| a Date object (section 15.9), in which case
| it behaves as if the hint were String.

From that quotation when you create instance object:

var obj = new MyDate();

For object referred by `obj' if call [[DefaultValue]] method with no
hint, will be treat as hint is Number.


Dr J R Stockton

unread,
Apr 19, 2010, 12:26:32 PM4/19/10
to
In comp.lang.javascript message <daa5afc9-f5d5-47ab-a4b2-3d68139f1029@8g
2000yqz.googlegroups.com>, Sun, 18 Apr 2010 12:52:49, nick
<nic...@fastmail.fm> posted:

>I decided to I wanted to subclass the native Date object, but realized
>that you can't call Date.prototype's function properties with anything
>but a 'pure' date object as the execution context. So, I decided to
>wrap all of Date.prototype's important functions, which worked out
>pretty well...

You might like to look at :
<URL:http://www.merlyn.demon.co.uk/js-dobj2.htm> Alt. date object
<URL:http://www.merlyn.demon.co.uk/js-datex.htm> Date errors
<URL:http://www.merlyn.demon.co.uk/js-dates.htm> Date index, ff.

Note that, when reporting unexpected results, it is well to indicate
which version of which browser (or other host) is in use, ditto for
operating system, and the location to which your system is set.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.

nick

unread,
Apr 19, 2010, 4:46:32 PM4/19/10
to
On Apr 19, 12:26 pm, Dr J R Stockton <reply1...@merlyn.demon.co.uk>
wrote:

>
> You might like to look at :
>   <URL:http://www.merlyn.demon.co.uk/js-dobj2.htm>   Alt. date object
>   <URL:http://www.merlyn.demon.co.uk/js-datex.htm>   Date errors
>   <URL:http://www.merlyn.demon.co.uk/js-dates.htm>   Date index, ff.

Nice... the thing I'm working on is a port of PHP's date() formatting;
looks like you've done something pretty similar. I'll post what I've
got in pastebin or something when I get home so you can have a look,
it might be interesting to you.

> Note that, when reporting unexpected results, it is well to indicate
> which version of which browser (or other host) is in use, ditto for
> operating system, and the location to which your system is set.

Good point. I believe I tested it in latest versions of GC and FF, but
I was on my way out the door when I got to that point so I may be
mistaken. The behavior I was noticing was basically:

(''+new Date) == (new Date).toString()
(''+new Date) != (new Date).valueOf()

(''+new MyDate) != (new MyDate).toString()
(''+new MyDate) == (new MyDate).valueOf()

This isn't what I expected (I expected ''+anything to be the same as
anything.toString() pretty much across the board), but it's probably a
result of my not having taken the time to fully understand the inner
workings of toString and valueOf.

I'll try to post something as little more coherent (and respond to
Asen, sorry Asen) when I get back to the house ;)

-- Nick

nick

unread,
Apr 19, 2010, 11:52:16 PM4/19/10
to
On Apr 18, 5:30 pm, Asen Bozhilov <asen.bozhi...@gmail.com> wrote:
...
> That design is not really good decision. It is memory inefficient and
> break forward compatible with non generics methods for Date
> instances.

True, but can you think of a more efficient way to to extend Date? Or
do you think I should scrap the idea of extending Date altogether and
instead make other classes / functions that act on instances of Date?

> By specification that is normal behavior, because Date instances have
> special [[DefaultValue]]. During evaluation of addition expression,
> objects will be converted to primitive value. For type converting will
> be use internal [[DefaultValue]] of that object, without passing hint
> argument.

Thanks for the explanation. Apparently only pure Date instances get
this special behavior, just being an 'instanceof Date' isn't good
enough.

I guess DefaultValue and hint are internal stuff I have no control
over?

[snip]

> For object referred by `obj' if call [[DefaultValue]] method with no
> hint, will be treat as hint is Number.

How can I call it with a hint... by doing something like
Number(myDate) or String(myDate)?

-- Nick

Johannes Baagoe

unread,
Apr 20, 2010, 12:19:56 AM4/20/10
to
nick :

> True, but can you think of a more efficient way to to extend Date? Or do
> you think I should scrap the idea of extending Date altogether and
> instead make other classes / functions that act on instances of Date?

When I had a similar project some time ago, what I finally decided (with
some help from this newsgroup) was not to subclass, but to combine. That
is, I made a conctructor that returned not an augmented Date object, but
an Object containing a Date object used internally by the various methods.

The result is here: http://baagoe.com/en/ES/XsDateTime.js

Feel free to criticise, copy and use.

--
Johannes

nick

unread,
Apr 20, 2010, 12:32:16 AM4/20/10
to
On Apr 20, 12:19 am, Johannes Baagoe <baa...@baagoe.com> wrote:
[...]

> When I had a similar project some time ago, what I finally decided (with
> some help from this newsgroup) was not to subclass, but to combine. That
> is, I made a conctructor that  returned not an augmented Date object, but
> an Object containing a Date object used internally by the various methods.
>
> The result is here:http://baagoe.com/en/ES/XsDateTime.js

We're doing a very similar thing, wrapping all the generic
functions :)

You wrote:

for (var i = 0; i < methods.length; i++) {
(function(method){
XsDateTime.prototype[method] = function() {
return Date.prototype[method].apply(this.date, arguments);
};
})(methods[i]);
}

I wrote:

for (var i=_nm.length; i--;) (function (f) {
base[f] = function() {
return Date.prototype[f].apply(this._date, arguments);
}
})(_nm[i]);

> Feel free to criticise, copy and use.

You stole my idea! Just kidding. But hey, I worked out the weirdness
with toString vs. valueOf... going to post about it in response to my
first post so it doesn't get lost.

-- Nick

nick

unread,
Apr 20, 2010, 12:39:33 AM4/20/10
to
I think I worked out. In the class prototype definition:

base.valueOf = function(){
return new Number(this._date.valueOf())
}

Looks like because valueOf returns an object and not a primitive,
toString gets used instead with the plus operator (just like Date
instances). MyDates seems to act just like Dates now (but they're
extendable).

-- Nick

Johannes Baagoe

unread,
Apr 20, 2010, 12:58:44 AM4/20/10
to
nick :

> But hey, I worked out the weirdness with toString vs. valueOf... going
> to post about it in response to my first post so it doesn't get lost.

As the second programmer told the first who asked "What does '\u0007' mean?",
I'm not sure, but it may ring a bell. I vaguely recall having encountered
that problem, but I don't remember if it was ever solved, or how. Your
explanation will be welcome.

Sorry about not having responded earlier, by the way, I was
concentrating on other matters.

--
Johannes

Asen Bozhilov

unread,
Apr 22, 2010, 4:40:38 PM4/22/10
to
nick wrote:
> Asen Bozhilov wrote:

> > By specification that is normal behavior, because Date instances have
> > special [[DefaultValue]]. During evaluation of addition expression,
> > objects will be converted to primitive value. For type converting will
> > be use internal [[DefaultValue]] of that object, without passing hint
> > argument.
>
> Thanks for the explanation. Apparently only pure Date instances get
> this special behavior, just being an 'instanceof Date' isn't good
> enough.
> I guess DefaultValue and hint are internal stuff I have no control
> over?

Internal methods are not inherited via prototype chain. For example
Function instance has internal [[Call]] and [[Construct]] which are
used during evaluation of `CallExpression` and `NewExpression`. If I
inherit from Function object, created object after that does not have
these internal methods because they are not inherited via prototype
chain. For example of my words:

function ExtendFunction() {}
ExtendFunction.prototype = function(){};

var f = new ExtendFunction();

print(f instanceof Function); //true

/* If object has [[Call]] method typeof
* must return primitive string value "function"
*/
print(typeof f == 'function'); //false

try {
f(); //Invoke internal [[Call]]
}catch (e) {
print(e instanceof TypeError); //true
}

try {
new f(); //Invoke internal [[Construct]]
}catch (e) {
print(e instanceof TypeError); //true
}

> > For object referred by `obj' if call [[DefaultValue]] method with no
> > hint, will be treat as hint is Number.
>
> How can I call it with a hint... by doing something like
> Number(myDate) or String(myDate)?

The question is to which value you want to convert that object? When
you answer on that question you can find way to do that conversion.
See:
<URL: http://www.jibbering.com/faq/faq_notes/type_convert.html /> By
Richard Cornford.

nick

unread,
Apr 22, 2010, 7:15:15 PM4/22/10
to
On Apr 22, 4:40 pm, Asen Bozhilov <asen.bozhi...@gmail.com> wrote:

> nick wrote:
> > I guess DefaultValue and hint are internal stuff I have no control
> > over?

> Internal methods are not inherited via prototype chain. [...]

I see what you mean. I have actually tested something very similar to
the example you gave, so it makes perfect sense to me. Thanks for
helping explain it.

> > > For object referred by `obj' if call [[DefaultValue]] method with no
> > > hint, will be treat as hint is Number.

> > How can I call it with a hint... by doing something like
> > Number(myDate) or String(myDate)?

> The question is to which value you want to convert that object? When
> you answer on that question you can find way to do that conversion.
> See:
> <URL:http://www.jibbering.com/faq/faq_notes/type_convert.html/> By
> Richard Cornford.

What I wanted to do was have (''+new MyDate) give the same result as
(''+new Date), with (new MyDate) and (new Date) still giving the same
values for .toString() and .valueOf().

I managed to accomplish this by having (new MyDate).valueOf() return a
new Number object instead of a number primitive, which seems to force
toString() as the default value... you can probably explain how this
works much better than I can though.

http://groups.google.com/group/comp.lang.javascript/msg/204f2f2d2fdb5403

0 new messages