In prototypal languages object can basically clone each other.
So, lets say we have a constructor function:
Bla = function()
{
this.a = 1;
}
I can create a new instance of that object like this: x = new Bla();. Now, x.a returns 1.
If I were to write Bla.prototype.b = 2, then x.b would return 2. But, why? If x "cloned" Bla, why can’t I just say that Bla.b = 2, without referencing the Bla.prototype, and still get the same functionality? Does this have something to do with the this keyword?
ECMAScript (JavaScript) supports "prototype-based inheritance". This means there is no differentiation between "class" and "instance" in JS.
Opposed to OOP in other languages, in JS a "class" and "instance" are basically the same thing:
When you define
Something, it is instanciated immediately (ready to use), but can also serve as a "prototype" to clone the initial(!) definition of the objectSometingfor another instance with the same properties and methods.In ECMAScript, everything is an object, even the objects initial definition. In other OOP languages, you have a "class" for the definition part.
The
prototypeobject is for the case when you want to extend the prototype of "Something" (read: "class"Something) after the initial definition and add the new property / function to all current and future instances ofSomething.If you are confused now, i think this code example may help to spot the difference:
As you see in the last example, the concept of "prototype" is necessary to avoid cloning the current "state" of your object.
If it wouldn’t be implemented this way, you would possibly end up with weird effects, because if the original object "Something" was used / modified before you clone it, then the current state would be copied as well. That is why the language designers went for the
prototypeconstruct.Always remember: "Something" isn’t a static definition, like "classes" are in other OOP languages.
The ECMAScript specification says about
prototype:Some JS frameworks like the equally named "prototype" make heavy use of this feature to extend the functionality of Javascripts built-in objects.
For example, it extends the native
arrayobject with the methodforEach, to add this missing feature to JS: