This code shows a contsructor at the top, which is used to create Person
objects by providing the parameters name
and age
. This object can be given more properties, such as hair color, height, weight, and much more. By using these objects, you can simply store all the objects in an array or list and this will provide for a psuedo database that could be use for the census bureau to keep track of people. Object-oriented programming is all about creating objects to store data instead of relying mainly on variables with each person's name before the variable.
For example, instead of:
var ericName = 'Eric';
var ericAge = '22';
You could do:
var eric = new Person('Eric', '22');
and this will create a Person object stored in the variable eric
. His age would be accessed by calling eric.name
and eric.age
. Object-oriented programming simplifies having so many variables into having just a few and having lots of methods to access their information and change it.
The next segment:
var ageDifference = function(person1, person2) {
return person1.age - person2.age;
}
should actually be rewritten as:
function getAgeDifference(person1, person2) {
return person1.age - person2.age;
}
To get the age difference between two people, you would call getAgeDifference(alice, billy);
. This calls the getAgeDifference
method that will use their age
properties to provide you with more information.
Object-oriented languages such as Java, C++, Objective-C, also make use of classes that help separate sections of relevant code into different classes or files. This idea of classes is very helpful yet hard to understand and if you are looking to learn a lot about it I would recommend picking up a book about a specific language and going along with the information it provides to give you an idea of how to write object-oriented code and some examples and guides of what to do each step of the way.
Good luck!