Getting to Learn JavaScript Objects - Part 1

Guest Posts Paolo Nikko Nuñal

Basically, the best way to practice programming is making your code object-oriented. JavaScript caters to object-oriented programming and here are some of the things that you should  know.

First of all everything in JavaScript is considered an object. And in JavaScript you can define your own object easily. Even primitive datatypes are also treated as objects.

So what is an object? Simple, it is a kind of data with properties and methods that you can assign to.

How to access object properties

objectName.propertyName

objectName - The name of the object, a variable.

propertyName - The name of the property you would like to access.

Example:

var text = "JavaScript";
var letters = text.length;


In our example above, the text is a variable that can be treated as an object and contains the string "JavaScript". The "text" is the objectName while the length is the propertyName. Since length is a property it returns the length of the object "text" which is 10.

Another way to create JavaScript Objects is using a direct instance approach. If you have tried Java before, then creating objects is the same as Java only with some minor code differences. But the logic is still the same.

person = new Object();
person.fname = "Mitchell";
person.age   = "24";


From the above code, we are stating that the variable "person" is a new object using the "new" keyword and Object() method. After which, we assign a propertyName which are fname, and age with the following value "Mitchell" and 24 respectively.

Another way to call an object is by using object literals.

person = {
      fname: "Mitchell",
      age  : 24
      };


Another way to do it is using a constructor the same as you with Java in creating objects.

function person(fname,lname){
this.fname = fname;
this.age   = age
}

p1 = new persone("Mitchell",24);


So don't be confused if you find other developers using different types of creating an object. We'll continue on the next tutorial.