0

JavaScript Object Creation and Object Methods and Properties

If you’ve read this, it merely declares JavaScript can do OOP. It did not talked about other (more advanced) OOP stuff like access modifiers, encapsulation – behaviors and properties, and inheritance. On this article, we’ll talk more on object creation, object functions (or methods) and properties.

“Class” in JavaScript

There is no keyword “class” in JavaScript that represents an object’s blueprint. To define a class, create a JavaScript function for that purpose.

The Person function can still be used like a normal function. To use it as a “class” and actually create an object, we use the keyword new with the function.

The Person object referenced by the personObject variable do not have behaviors and properties right now. We’ll add them up as we go along.

Object Properties

Object properties represent data stored in a object. An object can have any number of properties of different types. There are two ways to create properties – using var like a normal variable declaration (and assignment) and using the this keyword.

When var is used for variable declartion, that variable is not accessible outside of the object. This applies to functions too. For instance, the property name is not accessible outside of the object and any attempt to use it evaluates to undefined.

On the otherhand, using this makes a variable accessible outside of the object. This also applies to functions.

Object Behaviors

Object behaviors are created using the function keyword. The same way  functions are created for non-OOP purposes.

Executing the codes above outputs the following. The getName function is inaccessible outside of the class. This and the property name are the private members of the object. The getFavoriteNumber is, on the other hand, accessible outside of the class.

js-oop-20151030-1

So, how do we fix this error?

For the purpose of demonstration, we’ll keep the getName function and create another (using this) to return the private property name to codes outside of the object.

Executing the updated codes outputs the following.

js-oop-20151030-2

Summary

The functions and properties mentioned are members of anobject. They can be public, and private (inaccessible). Public members can be non-priviledged or priviledged. Priviledged members (e.g., function) have access private members. Non-priviledged members are defined using the prototype keyword and outside of the class. Priviledge member are defined using this and inside the class.

From our example codes, the private members are the property name and the function getName. The public members are the property favoriteNumber (priviledged member), functions getFavoriteNumber (non-priviledged member)  and getPersonName (priviledged member) .

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert