JavaScript 객체지향 정리

이재하·2023년 12월 19일
0

1. 객체와 프로퍼티:

자바스크립트에서 객체는 키와 값의 쌍으로 이루어진 프로퍼티들의 집합입니다. 객체의 프로퍼티는 다양한 데이터 타입의 값을 가질 수 있으며, 함수도 포함될 수 있습니다.

const person = {
  name: 'hyun',
  age: 7,
  sayHi: function() {
    console.log(`Hi ${this.name}`);
  }
};

이 예제에서 person 객체는 name과 age라는 프로퍼티를 가지고 있습니다. sayHi는 함수로, 이를 메서드라고 부릅니다.

2. 객체 생성 방법:

객체 리터럴:

const obj = {};

Object 생성자 함수:

const person = new Object();
person.name = 'hyun';
person.age = 7;
person.sayHi = function() {
  console.log(`Hi ${this.name}`);
};

생성자 함수:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.sayHi = function() {
    console.log(`Hi ${this.name}`);
  };
}

const person1 = new Person('hyun', 7);

ES6 클래스:

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

  sayHi() {
    console.log(`Hi ${this.name}`);
  }
}

const person1 = new Person('hyun', 7);

3. pass-by-value와 pass-by-reference:

원시 타입(pass-by-value):

let a = 5;
let b = a; // 값 복사
b = 10;
console.log(a); // 5 (a는 변경되지 않음)

참조 타입(pass-by-reference):

const obj1 = { name: 'hyun' };
const obj2 = obj1; // 주소 복사
obj2.name = 'yoon';
console.log(obj1.name); // 'yoon' (obj1도 변경됨)

4. ES6 클래스:

ES6 클래스는 생성자 함수와 프로토타입을 조합한 구조를 보다 간결하게 표현하는 방법입니다.

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

  sayHi() {
    console.log(`Hi ${this.name}`);
  }
}

const person1 = new Person('hyun', 7);

클래스는 생성자(constructor) 메서드를 포함하고, 다른 메서드들은 클래스 몸체에 정의됩니다. new 키워드를 사용하여 클래스의 인스턴스를 생성할 수 있습니다.

5. 클래스와 프로토타입:

클래스를 사용하면 프로토타입 기반의 상속을 더 간단하게 표현할 수 있습니다. 클래스의 메서드는 자동으로 프로토타입에 추가되므로, 인스턴스 간에 메서드를 공유할 수 있습니다.

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  bark() {
    console.log('Woof!');
  }
}

const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak(); // "Buddy makes a sound"
dog.bark();  // "Woof!"

extends 키워드를 사용하여 클래스를 상속할 수 있고, super 키워드를 사용하여 부모 클래스의 생성자를 호출할 수 있습니다.

이렇게 클래스를 사용하면 코드가 더 간결해지고 객체지향 프로그래밍의 개념을 더 직관적으로 표현할 수 있습니다. 클래스를 사용하면 생성자 함수와 프로토타입을 사용하는 것보다 코드가 읽기 쉬워지며, 코드의 재사용성도 높아집니다.

ref : https://velog.io/@duboo/JavaScript-%EA%B0%9D%EC%B2%B4-Object-%EC%B6%94%EA%B0%80-%EC%A0%95%EB%A6%AC-ES6-%ED%81%B4%EB%9E%98%EC%8A%A4

0개의 댓글