(newDate).getYear();// parentheses needed in a different place
But why are those parentheses needed at a different place? Why doesn't it just work without parentheses? How will I remember that I need to use this confusing syntax?
(newDate).getYear();
instead I could simply do
newDate().getYear();
This is what I am used to and it works.
Not giving you a hard time. There is a reason why you have to put the parentheses at a different place. It should be explained.
There is a reason why this works:
constx=newDate;// What I taught in this blog postconsole.log(x.toString());
And this does not
newDate.toString();
It's because new Date.toString() is not equal to new Date().toString(). *There is an extremely subtle difference. They have different precedence. *
new Date.toString() throws an error because . has higher precedence than new Date so the expression becomes (or it is resolved as) (new (Date.toString))(). They might look the same but they are evaluated differently!
In short, if you would like to invoke the constructor and chain it with a method in the object, the correct syntax is:
(newDate).toString();
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You said that we can omit parentheses in a parameter-less class constructor. This has gotchas.
You addressed this in your blog post by saying
But why are those parentheses needed at a different place? Why doesn't it just work without parentheses? How will I remember that I need to use this confusing syntax?
instead I could simply do
This is what I am used to and it works.
Not giving you a hard time. There is a reason why you have to put the parentheses at a different place. It should be explained.
There is a reason why this works:
And this does not
It's because
new Date.toString()
is not equal tonew Date().toString()
. *There is an extremely subtle difference. They have different precedence. *Check out: developer.mozilla.org/en-US/docs/W...
new Date.toString()
throws an error because.
has higher precedence thannew Date
so the expression becomes (or it is resolved as)(new (Date.toString))()
. They might look the same but they are evaluated differently!In short, if you would like to invoke the constructor and chain it with a method in the object, the correct syntax is: