Let’s first talk about functions. There are so many ways are there to define a function (which actually “inherits” an object) in JavaScript.
JavaScript treats functions and objects as first-class citizens, which means they can be defined, called, passed, returned, or do anything else much like you can do to a variable. Here are examples of how to declare a function (that I know).
One great thing about function as first class citizens is that they can be passed in to other functions as parameters.
This is a really contrived example. But, it does show how the add function can be passed into foo and called. A good example is the map function in some functional program languages, like in Scheme. map takes two parameters, first one a function, and second one a list, and it applies the function to every element of the list and spit out a new list
Objects
Objects are even more interesting. They can be pretty much declared in the same way as functions, but there’s a bit more to them.
The same can be done with a form similar to an anonymous function
Actually a function is an object
Adding function directly into the constructor looks like classes in other Object-Oriented Language, like Java or C++. However, it is not the optimal way of add functions in JavaScript Objects.
JavaScript is a prototypal language. So everything “inherits” an object. Student is a prototype created from Object. To add functions to an object efficiently is through using the .prototype.function property
By creating Object’s method through prototype is much faster because it is how JavaScript intended to process objects. Inheritance is simple, invoke this before adding any methods Student.prototype = Object.create(ParentObject.prototype);. Student prototype will be a copy of the prototype of another Object, so it “inherits” all the functionality of the other Object.