We help IT Professionals succeed at work.

Prototype in JavaScript

burnedfaceless
burnedfaceless used Ask the Experts™
on
Why would you add methods to an object via the Object's prototype?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
To make them available on that object whenever and wherever you need them.

For instance - let's say you want a method to format a date in a particular way.

Date.prototype.myFormat = function() {
  return this.getFullYear() + '-' + ('00' + (this.getMonth()+1)).substr(-2) + '-' + ('00' + this.getDate()).substr(-2);
}
var dt = new Date();
console.log(dt.myFormat());

Open in new window


You can now use myFormat() on any date object in the application. You have extended the default functionality for the object at a global level.

Author

Commented:
Thank you for your response.

Why not just add this method in the constructor?
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Why not just add this method in the constructor?

What if you don't have access to the constructor?

Author

Commented:
Thank you
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.