— Javascript — 3 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: 19975}67var temp = "author"89console.log(Book.author); // Prints "J. K. Rowling" to the console10console.log(Book['year']); // Prints "1997" to the console11console.log(Book[temp]); // Prints "J. K. Rowling" to the console12console.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: 74};56console.log(dog); // logs "{ name: 'Harry', age: 7 }" to the console7delete dog.age;8console.log(dog); // logs "{ name: 'Harry'}" to the console
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};910Human.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.
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};910Human.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.
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 : 1004}56function fn (p1,p2) {7 p1 = p1 - 1;8 p2.data = 90;9}1011fn(v,obj);1213console.log(v); // 1014console.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.
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}910var b1 = new book("Harry Potter and the Philosopher's Stone","J. K. Rowling",1997);11var b2 = new book("Book2","Author",1998);1213console.log(b1);14console.log(b2);1516b1.intro();
The 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!
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 }1213var p1 = new person("Henry");14console.log(p1.name); // Prints "Hi! I am Henry" to the console.1516delete p1.name; 17console.log(p1.name); // Prints "Hi! I am Henry" to the console.1819p1.name = "Harry";20console.log(p1.name); // Prints "Hi! I am Henry" to the console.
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.
Line no. 3–5 we have defined a getter function.
Line no. 6–8 we have defined a setter function.
Line no. 9 we have an attribute called configurable set to false, which doesn’t allow deletion of the “name” property.
Line no. 16 we have written code to delete the property, but as you can see it doesn’t work.
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!