I'm currently learning prototypes in Javascript and how we can add methods to existing objects using prototypes in Javascript. I tried adding a function to Date object using Prototype. Here's the code :
Date.prototype.getDayName = function () {
return new Date().toDateString().split(" ")[0];
};
The above code returns the name of the day for the current day
How do prebuilt functions like toDateString()
in Date Object return the date string for the particular day without having to pass arguments to the toDateString()
function? Like in the below example :
var date = new Date("11/03/2022");
date.toDateString();
How can I do the same with my getDayName()
function (the first code snippet in this question) ?
Edit: To be further clear, all I want to know is how does the below code work?
var date = new Date("11/03/2022");
date.toDateString();
// Returns 'Thu Nov 03 2022'
How does date.toDateString()
return the string value of the date even though no argument is passed onto the .toDateString()
method?