ReasonJun

What is different 'class' and 'object' in javascript? 본문

Frontend/Javasciprt

What is different 'class' and 'object' in javascript?

ReasonJun 2023. 6. 10. 12:52
728x90
  • Object:

An object is a fundamental concept in JavaScript and is an instance of a particular class or a collection of key-value pairs. Objects can be created using object literals ({}), the Object() constructor, or by instantiating a class using the new keyword.

const person = {
  name: 'John',
  age: 30,
};

console.log(person.name); // Output: John

In the example above, person is an object created using an object literal notation. It has properties name and age. Objects can have their own properties and methods defined.

  • Class:

A class in JavaScript is a blueprint or a template for creating objects. It encapsulates the common properties and methods that objects of the same type should have. Classes define the structure and behavior of objects.

Starting from ECMAScript 2015 (ES6), JavaScript introduced a class syntax that allows you to define classes using the class keyword. However, it's important to note that JavaScript's class implementation is built on top of JavaScript's prototype-based object model.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const john = new Person('John', 30);
john.greet(); // Output: Hello, my name is John and I am 30 years old.

In the example above, Person is a class that defines the structure of a person object. It has a constructor to set the initial state of the object and a greet method that can be called on instances of the class.

When a class is instantiated using the new keyword, it creates an object based on the class's blueprint, and the object is an instance of that class.

 

In summary, an object is an instance of a class or a collection of key-value pairs, while a class is a blueprint or template that defines the structure and behavior of objects. Classes provide a way to create multiple instances of objects with the same structure and behavior.

728x90

'Frontend > Javasciprt' 카테고리의 다른 글

javascript : regexp pattern  (0) 2023.06.09
javascript : Regular expression (test, match, replace)  (0) 2023.06.09
javascript : Web API (location)  (0) 2023.06.09
javascript : Web API (history)  (0) 2023.06.09
javascript : Web APIs (storage)  (0) 2023.06.09
Comments