There are four rules or main pillars of Object-oriented programming language. This defines how the data and actions associated with the data; are organized using code.
Let's look at the ES6 way of defining classes, using the class keyword and then we'll see how classes were defined traditionally.
This way, we create a class using the class keyword. Define constructor function and all the other data functions inside the class declaration function. Then we create instances for this class using the new keyword.
An object is a data structure containing properties and methods. Consider a student. A student will have characteristics like name, roll number, and class, and he will perform an action, let's say, giving an exam. In object-oriented programming, these characteristics are called data variables. These actions are called data methods.
We create a class called Student and then create instances of this class. These instances are called Objects. Hence, an object is a real instance of a class. Class is nothing but a prototype/blueprint.
Encapsulation puts the data variables and the data functions together inside a box. Encapsulation ensures that data can only be accessed using the data functions defined inside the class, and abstraction ensures that no one outside this encapsulated box can access it.
Let's discuss both of them with examples.
When we define a variable or a function inside the function, we can only access it from inside and not from outside the function. This can be one way of implementing abstraction. Look at the example below.
The output for this code snippet says the right message when accessed from inside but throws an error when accessed from outside. Hence, the message is encapsulated.
We can create a function inside a function, and the inner function will be able to access the local variable defined inside the outer function. This is called closure.
Note: A closure is created every time a function is declared.
Again, the output says that creating a closure helps encapsulate and restrict the data access only to inside the function.
Let's create an object and console it.
We only defined the property name, age & mobile to the user Object, but we can see a lot of other methods. We didn't define them! These methods are inherited from the parent object, i.e., the prototype for the object data structure. When we create the object user Object, we basically inherit all the properties object data structure.
In this comprehensive guide to SOLID design principle, we talk about the five fundamental principles to transform your software development skills to ensure that your code is efficient, flexible and scalable.
In this blog, we explore how WebAssembly, in tandem with the power of Rust programming, is transforming modern web development.