OOPs Concepts
JavaScript is an object-oriented programming language, but it uses a different model than most other object-oriented languages, such as Java or C#. JavaScript uses prototypes instead of classes for inheritance, which is a form of object-oriented inheritance that relies on shared objects.
Here are the main concepts of object-oriented programming in JavaScript:
- Objects: In JavaScript, an object is a standalone entity, with properties and type. It can be seen as a container that holds related data and methods used to manipulate that data. You can create an object using the object literal syntax or the new keyword.
- Properties: A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object.
- Methods: Methods are functions that are associated with an object. They define the behaviors or functionalities that an object can perform.
- Prototype Inheritance: In JavaScript, each object has a prototype object, which acts as a template object from which it inherits methods and properties. An object’s prototype object may also have a prototype object, from which it inherits methods and properties, and so on. This is often referred to as a prototype chain.
- Constructors: In JavaScript, the constructor method is a special method for creating and initializing an object. A constructor can use the this keyword to reference the object that will be created and initialized.
- thisKeyword: In JavaScript, this is a special keyword that is used in methods to refer to the object on which a method is called. It's a reference to the object the method was called upon.
- Encapsulation: This is the practice of keeping fields within a JavaScript object private, so they can only be accessed and modified through methods of their containing object. This is usually done by defining them as local variables within the object constructor.
- Polymorphism: While JavaScript doesn't support polymorphism in the traditional sense due to lack of type-checking, it can achieve a similar outcome because it's dynamically typed. This means you can overwrite or change methods and properties in a way that's more flexible than in statically typed languages.
Note
Note that with the introduction of ES6 (ECMAScript 2015), JavaScript introduced aclass
syntax that allows developers to write classes that work much like they do in other object-oriented languages. However, it's important to understand that under the hood, this is just syntactic sugar, and JavaScript still uses prototypes for inheritance.