Deep understanding of classes in JavaScript

Tram Ho

The concept of Class in object-oriented programming languages ​​like Class in Javascript is used a lot but in JavaScript under ES6 there is no concept of Class . JavaScript uses the Prototype property of its Objects for object-oriented purposes. We will learn these concepts in the article Deeply Understand Classes in JavaScript

1. What is object-oriented programming?

Object Oriented Programming (OOP) is one of the most important and widely used programming techniques today. Most of today’s programming languages ​​such as Java, PHP, .NET, Ruby, Python… all support OOP.
Specifically: Object-oriented programming (OOP) is a programming technique that allows programmers to create objects in code that abstracts away objects. There are two concepts to grasp here:

  1. Class(class): this is the basis, the so-called abstraction of the object. For example, the Nam object is created from the Person class.
  2. Object: the opposite is the materialization of the class.
  3. Attributes: properties of the object such as the object Nam whose property name is Nam. When you don’t understand, reading these 2 sentences sounds like a crazy train. What is abstraction and concretization? Here is an example.

The example above creates a Person class , which is an abstraction. A class as a blueprint can create multiple copies with specific properties such as the names of two Nam and Nam2 objects created from the same blueprint, the Person class.

2. Object Oriented Programming in JavaScript

  • Most JavaScript elements are Objects .
  • You can see simple variable declarations: let a=1. Why does variable a have a.toString() function when we don’t define a function for that variable at all. Actually let a=1 is a shortcut declaration, explicitly declared variable a will be written as follows: image.png
  • So the variable or function declarations you are using are actually short declarations of the variable or function creation. They are in fact an object created by a Class and using the new operator.
  • You can view the properties inherited by the a object from the Number class via the prototype via the __ proto property. All JavaScript objects have this property image.png
    So it was Prototye that created inheritance in JavaScript

3. Constructor Function and operator new

A constructor is a function used to initialize properties for objects (Object). The constructor will have the same name as the class when you declare the class in ES6. Eg:

Share the news now

Source : Viblo