previousnext

Having too many global variables is considered to be bad programming styles. One approach that is used is known as Object-Oriented Programming (OOP) in which variables that belong to an object are encapsulated, i.e. packaged within that object, [mostly] hidden from outside that object, and known as the attributes of that object. Similarly, the actions which that object can perform (known as methods) are also packaged with that object.

In javascript, a common approach to OOP is to use function() to create objects. In our example, we have one obvious object: the ball. Below is one way in which we can create a javascript class of objects to describe the ball.

By convention, we describe a class of objects with a name that starts with an upper case letter (Ball), and denotes instances of that class with names that start with a lower case letter (ball).

By judiciously choosing the names of our object methods, we have made some previously written comments completely redundant: they essentially just repeat what the code says; in the future, we will remove such redundant comments.

Experiment!

  • Verify that the code works as before.
  • Compare the new code with the previous version available in the "pre" tab of the editor.
  • You can change the main code and run it; however, changes in the code from the previous version will have no effect when you run the code.

Notes

If you have not seen the javascript keyword this before, mentally replace it by synonym_to_the_name_of_the_instance_that_will_be_created. Thus, when writing ball = new Ball(...) it is as though all this were replaced by ball. If you create a second instance, say ball_2, a new object is created where this is effectively ball_2.

previousnext