Frontend Development: Class

Peter Jeon·2023년 7월 5일
0

Frontend Development

목록 보기
41/80
post-custom-banner

Classes in JavaScript are a template for creating objects. They encapsulate data with code to work on that data. Introduced in ECMAScript 2015 (ES6), classes provide a syntax more consistent with other programming languages.

Class vs Function

AspectsClassFunction
Declarationclass Example {}function example() {}
Instantiationnew Example()example()
Property/Method DefinitionInside class bodyInside function body or prototype
InheritanceExtends keywordPrototype chain

Class Definition

A class is defined using the class keyword, followed by the name of the class. Here's an example:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

In this example, Rectangle is a class representing rectangular objects.

Constructor and Method

The constructor method is a special method for creating and initializing an object created within a class. It can include any number of parameters.

Class methods (like the area method below) can be defined inside the class definition.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  area() {
    return this.height * this.width;
  }
}

Class Instantiation

A class is instantiated (i.e., an object is created from the class) using the new keyword:

let rect = new Rectangle(10, 5);
console.log(rect.area()); // 50

Conclusion

The class syntax in JavaScript is a powerful and flexible tool that brings traditional object-oriented features to JavaScript. It is syntactic sugar over the existing prototypal inheritance and constructor functions, but offers a more straightforward and clear syntax. Understanding and utilizing classes effectively can lead to cleaner, more readable code and can help make JavaScript a more approachable language for developers coming from other object-oriented languages.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글