JavaScript/Object Oriented Programming

Previous: Regular Expressions Index Next: Constructors and Prototypes

Object Oriented ProgrammingEdit

The purpose of an object oriented design is to allow the components to be as modular as possible. In particular, when a new object type is created, it is expected that it should work without problem when placed in a different environment or new programming project. The result of this is a reduced time spent in redevelopment.

JavaScript uses objects to represent complex data types. Some objects are created manually, while others are built-in to the language itself, like the Date object. Objects are small structures of data with their own fields and functions to access or modify these fields. A benefit of objects is that they use a "black box" approach where the internal variables are protected from most forms of outside interference. This helps to prevent them from being altered by program code outside of the function or object, which provides a better integrity for the data itself.

Unlike other programming languages, JavaScript does not provide implicit protection levels on members of an object. In particular, JavaScript uses a prototypical form of Objects, which can still inherit from parent classes, but is not a pure form of an object oriented language. However, most design patterns can still apply within the language as long as there is no attempt to directly access the object's internal state (for example, using an object's methods.)

As with many other programming languages, objects in JavaScript have their fields and functions referenced by the dot (.) between the object and field name.

The new operatorEdit

The new operator creates a new instance of an object.

item = new Object();

Object methods and fieldsEdit

In JavaScript, objects are free form - they can be modified at run time to instantly create a new object or to create new fields or functions.

money = new Object();
money.quarters = 10;

Object LiteralsEdit

Objects can also be created using the object literal notation.

money = {
    'quarters': 10
};

As shown below, you can create a function for an object in the same manner.

The this keywordEdit

The this keyword is used as a reference to an object for which a method was called.

money = {
    'quarters': 10,
    'addQuarters': function(amount) {
        this.quarters += amount;
    }
};
money.addQuarters(10);

The total number of quarters would now be twenty.

Previous: Regular Expressions Index Next: Constructors and Prototypes
Last modified on 6 December 2013, at 07:15