16 April 2016
This could be a large blog entry, there is so much consider when it comes to objects in javascript.
What I have learned that triggered this blog:
The constructor function is the prototype for an object. For some reason, I had thought the two were seperate.
Also, the constructor function is not restricted to assigning properties to the instance of the prototype, it can do other things like contain variables just like other functions do, that will not be part of the object once it’s created (free code camp person example. For example, the advance algorithm challenge on free code camp tripped me up for quite some time, but the resulting contractor function was:
var Person = function(firstAndLast) {
var firstName = firstAndLast.split(" ").shift();
var lastName = firstAndLast.split(" ").pop();
this.getFirstName = function() {
return firstName;
};
this.setFirstName = function(first) {
firstName = first;
};
We can change the prototype if we wanted, which will also change all the instances of that object prototype: Person.prototype.nationality = “”;
Now all Persons created by the constructor will have a nationality defaulted to “”. This is because each Person ‘inherits’ from the Person prototype.
By using prototypes and object inheritance, we can effectively create classes in javascript, in the same way other programming languages do. The example on MDN is hard to make sense of as a beginner, but I think I have my head round it now.
Creating inheritance between two object prototypes is very powerful, and simple to achieve. For example, say we create a parent object prototype. Then we want to make a child object prototype. To make the child inherit the characteristics of the parent prototype, we need to have the following code somewhere after the prototype function:
child.prototype = new parent();
This creates a new instance of the parent prototype, inside the child object. Now the child will inherit all the characteristics of the parent.
Alternatively, we can call the parent constructor inside the child constructor with:
Parent.call(this);
this will also create inheritance.
If we want to create inheritance and pass property values up the inheritance chain, it requires a little more code (note the word father is nothing special, it can be anything:
this.father = Parent;
this.father(value, value, value);
These lines in an object constructor (prototype) will also create inheritance, as well has share the values passed to the child object, on to the parent object.
MIND. BLOWN.