Posts

Inheritance

  Inheritance is a fundamental concept in object-oriented programming (OOP) that allows developers to create a new class that inherits properties and methods from an existing class. In JavaScript, inheritance is achieved by using the prototype property and the Object.create() method. JavaScript uses a prototype-based inheritance model, which means that objects can inherit properties and methods from other objects. Each object has a prototype property that refers to another object, and properties and methods are inherited by traversing the prototype chain. For example, consider the following code: function Person ( name , age ) { this .name = name; this .age = age; } Person . prototype . greet = function () { return `Hello, my name is ${ this . name } and I am ${ this . age } years old.` ; } function Student ( name , age , major ) { Person. call ( this , name, age); this .major = major; } Student . prototype = Object. create ( Person . prototype )...

Encapsulation

  Encapsulation is a fundamental concept in object-oriented programming (OOP) that refers to the practice of hiding the internal details of an object from other objects and code. In JavaScript, encapsulation is achieved by using closures and access modifiers, such as the private and public keywords. JavaScript uses closures to implement encapsulation, which allows developers to create private variables and methods that cannot be accessed from outside the object. For example, consider the following code: function Person ( name , age ) { let privateAge = age; this .name = name; this . getAge = function () { return privateAge; } } let person = new Person ( "John" , 30 ); console. log (person.name); // "John" console. log (person.privateAge); // undefined console. log (person. getAge ()); // 30 In this example, the privateAge variable is defined inside the constructor function and can only be accessed using the getAge method. This...