Object Oriented Programming Java Script Style Part-2

ยท

2 min read

in last part of document, we saw how javascript supports Object Oriented Programming paradigm, and how its features come into action, differently in javascript. In today's lesson we'll learn more about how classes are used, how to create them in javascript, what are constructors and finally what are objects.

this Link simply tells how to create a Class in javascript. explanation of the above code, in JS and many other languages we can create classes by using the keyword class, as we declare a variable, in the same manner we declare classes.

var name="tommy" // variable declaration

class Student { 
//encapsulation happens here
}

congratulations we have successfully created a class ๐ŸŽ‰ but now we need to use them ๐Ÿค”, Answer to this question is Objects, they are one's who use classes. hmm so what are objects? so objects are nothing but "Classes in action", explaining this in simple words would be something like, there's an architect bob and his job is to design blueprint according to requirements, get it verified and later using the blueprint, construct the actual house, in the below link we can see how a object is created in JS Object-creation explanation of the above code

//using the keyword class we have created a class named as student
class Student{
name="Tommy";
  age=23;
  gender="Male";
}

/*here using the new keyword we have 
created an Object of/from class Student*/
var myNewStudent= new Student(); 

/*we can also check that myNewStudent comes from 
which class using the 'instanceof' keyword*/
console.log( myNewStudent instanceof Student) 
//prints "True" on the console

bob1.png so now what if bob wants to create another house which has same specifications, but will it be exactly same as the previous one, the answer is a big NO, its just that the specifications of both house will be same that's it, but how ?? so here comes a new concept that is a constructor, a constructor is a function that runs, when javascript has created a new object and the constructor function will run on top of it and make changes in this object, in other words when an object is in initialization phase that's when constructor gets called , hence now we can create many object but with different details/values although constructor aren't mandatory to be present in the class, but even if you don't provide any the javascript implicitly defines one constructor with no definition.

Woahhh so today we covered a more about classes, got introduced to Objects and Constructors in the next which will be final part we'll cover more about Object, constructors and more coding examples.

Thank you so much for giving it a read and staying uptill end

ย