Skip to content

Kanishkar J

Object Oriented Javascript

Javascript3 min read

Object Oriented programming in Javascript is a bit weird, classes are not defined in javascript unlike languages like C++, java or python. That’s, as of ECMAScript5, the Class keyword has been introduced in the ECMAScript6 definition. But it’s just a syntactical sugar over the original object definition in Javascript. Hence it is important that every Javascript developer knows how objects work.

In JavaScript, an object is an unordered collection of properties. Each property consists of a key/value pair, and can reference either a primitive (e.g., strings, numbers, booleans, etc.) or another object. Unlike elements in an array, which are accessed by a numeric index, properties in objects are accessed by their key name using either square bracket notation or dot notation.

1var Book = {
2 name: "Harry Potter and the Philosopher's Stone",
3 author: "J. K. Rowling",
4 year: 1997
5}
6
7var temp = "author"
8
9console.log(Book.author); // Prints "J. K. Rowling" to the console
10console.log(Book['year']); // Prints "1997" to the console
11console.log(Book[temp]); // Prints "J. K. Rowling" to the console
12console.log(Book.temp); // Prints "undefined" to the console

The above code was a representation of an object in Javascript, and different ways to get the attributes from the object.

  • Line no 1 to 5 the object is defined If you notice the object definition is similar to dictionaries in python. They are basically key-value pairs.

  • Line 9 logs the author of the book object via dot notation.

  • Line 10 logs the year of the book object via square bracket notation.

  • Line 11 is similar to line 10, except that instead of having the string inside the square brackets we have a variable that stores the string.

  • Line 12 is similar to line 9, except that instead of having the actual attribute we have a variable called temp which has the attribute name as a string assigned to it. And as you can see, it doesn’t work.

So what if you wanted to remove an attribute from an object. it’s simple as this :

1var dog = {
2 name: "Harry",
3 age: 7
4};
5
6console.log(dog); // logs "{ name: 'Harry', age: 7 }" to the console
7delete dog.age;
8console.log(dog); // logs "{ name: 'Harry'}" to the console

Defining methods inside objects

Methods are nothing but functions defined inside objects. Take a look at the code snippet below :

1var Human = {
2 name: "Harry",
3 age: 7,
4 gender: 'MALE',
5 hello: function (){
6 console.log("Hello!");
7 }
8};
9
10Human.hello(); // prints "Hello!" onto the console.
11Human['hello'](); // prints "Hello!" onto the console.

In here, we have defined an object called Human, with a method hello; that just logs “Hello!” onto the console.

  • Line no. 10 and 11 show how you can call these methods in your program. Note that they can be called via both the dot notation and the square brackets notation.

But what if we want to access the properties of the object in these methods? Look at the code snippet below :

1var Human = {
2 name: "Harry",
3 age: 7,
4 gender: 'MALE',
5 hello: function (){
6 console.log(`Hello! I am ${this.name}.`);
7 }
8};
9
10Human.hello(); // prints "Hello! I am Harry." onto the console.

The this keyword comes to our rescue. this keyword points to the object from which the method is called, hence giving access to all the properties defined in the object.

Immutability

In Javascript objects are mutable by default and primary data-types are immutable. i.e. if passed to a function the actual variable is passed in case of primary data-types while a reference is passed in case of object. Look at the code snippet below :

1var v = 10;
2var obj = {
3 data : 100
4}
5
6function fn (p1,p2) {
7 p1 = p1 - 1;
8 p2.data = 90;
9}
10
11fn(v,obj);
12
13console.log(v); // 10
14console.log(obj); // { data: 90 }

If you notice the variable v is not affected by the function, while obj.data is changed after the function call. This is because primary data-types (like v) are passed by value while objects (like obj) are passed by reference.

Constructor

If you have worked with OOP languages like C++, you would know that classes have constructors. They are functions that initialize and return objects. Let’s look at a constructor in Javascript :

1function book(name, author, year) {
2 this.name = name;
3 this.author = author;
4 this.year = year;
5 this.intro = function (){
6 console.log(`${this.name}, written by ${this.author} on ${this.year}`);
7 }
8}
9
10var b1 = new book("Harry Potter and the Philosopher's Stone","J. K. Rowling",1997);
11var b2 = new book("Book2","Author",1998);
12
13console.log(b1);
14console.log(b2);
15
16b1.intro();

The outputThe output

Did you see what we did there? we created a new object using a constructor. The function when passed arguments, returns a new object after assigning some attributes. New objects can be instantiated like how its done in line 10 and 11. Also, note we have used the new operator with the constructor. It’s important to use the new keyword before constructors if we accidentally forget “new” we will be modifying the global object instead of the newly created object. Take a look at the output, you can see that new objects are created, Hurray!

Object.defineProperty()

The Object.defineProperty() function can be used to define a new / edit an existing property on any object. Click here to read more about it.

1function person(name) {
2 Object.defineProperty(this, "name", {
3 get: function() {
4 return "Hi! I am " + name;
5 },
6 set: function(newName) {
7 name = newName;
8 },
9 configurable: false
10 });
11 }
12
13var p1 = new person("Henry");
14console.log(p1.name); // Prints "Hi! I am Henry" to the console.
15
16delete p1.name;
17console.log(p1.name); // Prints "Hi! I am Henry" to the console.
18
19p1.name = "Harry";
20console.log(p1.name); // Prints "Hi! I am Henry" to the console.
  1. Line no. 2–10 we have called the Object.defineProperty() method, with the params :
  • this : indicating we want the property set for the object referenced via the this keyword.

  • name : The attribute which we would like to define. Then we have a configuration JSON object.

  1. Line no. 3–5 we have defined a getter function.

  2. Line no. 6–8 we have defined a setter function.

  3. Line no. 9 we have an attribute called configurable set to false, which doesn’t allow deletion of the “name” property.

  4. Line no. 16 we have written code to delete the property, but as you can see it doesn’t work.

  5. Line no. 19 we have modified the name property of the object, which is works!

Okay! so that’s all about OOP, concepts of inheritance and data-hiding via closures has been explained in different posts. check it out!