Although JavaScript is a Class-Free language, it supports objects creation, overriding properties/methods and inheritance. In this post, we will explore the concepts of object creation and inheritance.
In JavaScript, Objects can be created in three possible ways:
- An object as literal
- Using the function constructor
- Using the Object.Create method
Object as literal
A simple object Student – as an object literal – can be created as shown in the listing below:
var Student = { name: "dj", age: 32, Father: { 'name': 'Ram', 'occupation': 'service' }, Subjects: [{ name: "Physics", marks: 89 }, { name: "Chemistry", marks: 95 }] };
Above we have created an object called Student. There are three types of properties attached to Student: simple properties like name and age, complex properties like “Father”, and an array property called Subjects. We can read properties as shown in the listing below:
console.log(Student.Father.name); for (var i in Student.Subjects) { console.log(Student.Subjects[i].name); }
We can also have a function serve as the property of an object, which is known as the method. So let’s say we want to attach a method “Speak” to the Student object. We can add the Speak method as shown in the listing below.
var Student = { name: "dj", age: 32, }; Student.Speak = function (message) { var finalMessage = this.name + " has said :" + message; console.log(finalMessage); }; Student.Speak("I am the best");
On calling Speak function as method, we will get output as shown in the image below:
There are some important points about the Speak method to remember:
- Properties can be added to an object at any time; a property can be added to an object after its creation too. For example, we added the Speak property later to Student object, rather than at the time of object creation.
- In the object’s method, the object is defined by value “this”. That is why we are able to print the name of the Student using this.name in the method.
- Calling a function as method is known as “Method Invocation Pattern”
In the above example, we are calling the Speak method on the object “Student”. So the value ofthis inside the Speak method is the Student object.
If we want to pass some other object as the value of “this” in the method, we can use the apply or call function. For example, we have one more object called Parents and,
- We are calling the Speak method of the Student object directly and the value of “this” in the Speak method would be Student.
- We are passing Parent as the value of “this” in the Student object’s Speak method. We are using the apply function to call the Student object’s Speak method and passing the Parent object as the value of this.
Leave a Reply