I'm relatively new in javaScript and I was doing some inheritance. I thought I know what prototype is but then i met with uber method. Now I don't know the difference between those two. I know that uber is like super in java and that's all. But then prototype is something that bothers me. If you can give me some simple example of using those two I would appreciate it very.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
Prototypes allow you to easily define methods to all instances of a particular object. The beauty is that the method is applied to the prototype, so it is only stored in the memory once, but every instance of the object has access to it.
There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.
Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.
uber
is just a sugar method Douglas Crockford created in his examples of inheritance in JavaScript which should help the devoloper when working with the very, very flexible nature of JavaScripts prototypal inheritance.
This method doesn't exist in native JavaScript.
He explains the sugar methods he uses in detail here.
In his examples he defines the uber
method as a helper method to access the parent implementation of a method.
Let's assume that you have a "class" (I use this term to ease the example; strictly spoken there are no classes in JavaScript) Human
which has a walk
method. If you now "extend" this class in an Infant
class, you could overwrite walk
in such a way that the infant only crawls since it can't walk.
It's obviously not a great example but I hope you get the point.
In such a case you could use Douglas Crockfords uber
method to access the Human
implementation of walk
in the Infant
"class".
To compare JavaScripts native prototype
object and Douglas Crockfords uber
method would make no sense, since both serve completly different purposes.
If you want more information on JavaScripts prototype
you can take a look at this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With