Not much of an issue, but it falls under wat so I'm super curious.
If you make a new Date in JS and then refer to it then it returns what looks like the value of the date instead of a description of it's properties (IE: Date{date: "some date"}
) like other objects do. It seems to be acting like a value instead of an object, yet it most definitely is an object. Chrome's inspector also helps to point that out with the text color change, and the lack of " "
around it since it's not a string.
IE:
let date = new Date()
let person = {
name: 'mike'
}
console.log(person) // {name:"mike"} or: Person {name:"mike"} <- obj description
console.log(person.name) // "mike" <- value
console.log(date) // Tue Jul 17 2018 22:53:29 GMT-0700 (Pacific Daylight Time) <- value??
// Why no description?
date.test = 'testing'
console.log(date) // Same as above, no description, but the property IS there.
console.dir(date) // Shows the object in a tree like it does with other objs.
// Note : The behavior for person is similar when used with a constructor instead of an object literal.
I know that if you excludes the new
keyword and just say let date = Date()
it returns a string instead, so I am guessing that the value we see when we reference it using new Date()
is the object's Type or the name of it's constructor? Regardless, why don't we see the object's properties when it's referenced like we do with other objects, or at least in the same format?
Also, if you use string interpolation, IE: The current date is ${date}
it also works, substituting the date into the string correctly, whereas if I tried that with the person object above it break. Using a constructor instead of an object literal would put [object Object] in the string instead.
I know in some languages like C# you can override an object's ToString() method, and that ToString() method is used as a default in string interpolation. Is something similar to that going on here?
Also curious what the Date constructor is returning. It seems like it's returning an object, and if you check typeof(date)
you'll see that it's an object, but it doesn't seem to be behaving quite like other objects. At least not when it's referenced. Seems like the variable date is pointing to an object but also pointing to it's value?
However if you console.dir(date)
the date, it looks like it's constructor's name is the date itself, like a dynamic constructor of some sort. Odd. Any thoughts?
tldr; Why does the Date object act differently than other objects when referenced? Should mention that it does the same thing in a REPL like Node.