How does JavaScript .prototype work? How does JavaScript .prototype work? javascript javascript

How does JavaScript .prototype work?


In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.

Example:

//Define a functional object to hold persons in JavaScriptvar Person = function(name) {  this.name = name;};//Add dynamically to the already defined object a new getterPerson.prototype.getName = function() {  return this.name;};//Create a new object of type Personvar john = new Person("John");//Try the getteralert(john.getName());//If now I modify person, also John gets the updatesPerson.prototype.sayMyName = function() {  alert('Hello, my name is ' + this.getName());};//Call the new method on johnjohn.sayMyName();