2

I am trying to learn JavaScript. In order to use some methods of the Number object on the Developer Mozilla, it is necessary to write a .prototype. What does prototype here mean and why should it be used? Can you give a proper explanation for someone new to the programing language?

enter image description here

SoF
  • 729
  • 1
  • 10
  • 24
  • 1
    _"In order to use some methods of the Number object [...] it is necessary to write a .prototype."_ - no, it is not. _"What does prototype here mean"_ - https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes – CBroe Jun 09 '22 at 11:43
  • 1
    This article might give you some insights about prototyping -> https://www.geeksforgeeks.org/prototype-in-javascript/ – iLuvLogix Jun 09 '22 at 11:44

1 Answers1

2

Some commenters directed you to resources with more information about prototypes in JavaScript, and there is also more information about the topic on the answers for this StackOverflow question.

However, let's try to give a simple answer to the question at hand.

It should be noted that while the prototype methods are very common to use, you rarely explicitly type something like Number.prototype.

On JavaScript, each object (including objects that represent primitive values like numbers) has a prototype object from which it inherits properties and methods. The prototype is almost always an actual object though it may also be Null.

Number values, like 0 or 235.5, have the Number object as their prototype.
Now, it may be a bit confusing, but Number.prototype does not refer to the prototype of the Number object. Instead, it is what the Number object provides when used as a prototype, to it's instance objects. So if, for example, you write (23).toLocaleString()1, then you are calling the method toLocaleString of the object 23, which inherits it from the Number object.

1: The reason we have to add parentheses around 23 is because the . would otherwise be interpreted as decimal point, resulting in a syntax error. Another option would be to write 23..toLocaleString() where the first dot would be a trailing decimal point (23. is a valid way to write 23 in JavaScript) and the second dot would be used for the property access.

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Noam
  • 1,317
  • 5
  • 16