Basics

const person = {
  name: ["Bob", "Smith"],
  age: 32,
  bio: function () {
    console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
  },
  introduceSelf: function () {
    console.log(`Hi! I'm ${this.name[0]}.`);
  },
};

person.name;
person.name[0];
person.age;
person.bio();
// "Bob Smith is 32 years old."
person.introduceSelf();
// "Hi! I'm Bob."

// Same thing
const person = {
  name: ["Bob", "Smith"],
  age: 32,
  bio() {
    console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
  },
  introduceSelf() {
    console.log(`Hi! I'm ${this.name[0]}.`);
  },
};

Terms

The value of an object member can be pretty much anything — in our person object we've got a number, an array, and two functions.

The first two items are data items, and are referred to as the object's properties. The last two items are functions that allow the object to do something with that data, and are referred to as the object's methods.

An object like this is referred to as an 🔥object literal — we've literally written out the object contents as we've come to create it. This is different compared to objects instantiated from classes, which we'll look at later on.

prototypes

JavaScript는 프로토타입 기반 언어입니다. 이는 JavaScript에서 객체 지향 프로그래밍이 프로토타입을 기반으로 한다는 것을 의미합니다. 다른 언어들이 클래스(class)를 사용하여 객체를 생성하는 반면, JavaScript는 프로토타입을 사용합니다

간단히 설명하면, JavaScript에서는 모든 객체가 다른 객체로부터 상속된다는 개념이 중요합니다. 이때 상속의 기반이 되는 것이 프로토타입입니다.

객체는 프로토타입 객체를 가지고 있고, 이를 통해 다른 객체로부터 속성과 메서드를 상속받습니다. 객체를 생성할 때, 해당 객체의 프로토타입을 지정하거나 기존 객체를 수정하여 새로운 객체를 만들 수 있습니다.

// 프로토타입 객체 생성
var animal = {
  eat: function () {
    console.log("먹다");
  },
};

// 새로운 객체 생성 및 프로토타입 지정
var dog = Object.create(animal);
dog.bark = function () {
  console.log("짖다");
};

dog.eat();  // "먹다"
dog.bark(); // "짖다"

이 예제에서 dog 객체는 animal 객체를 프로토타입으로 가지고 있습니다. 따라서 **dog**는 eat 메서드를 상속받아 사용할 수 있습니다.

이러한 프로토타입 기반의 접근 방식은 JavaScript를 유연하게 만들어주며, 클래스 기반 언어와는 다른 개념을 가지고 있습니다. ES6부터는 클래스(class) 문법이 추가되었지만 여전히 프로토타입도 함께 사용할 수 있습니다.

정의하기

일반적인 방식으로는 속성은 생성자에서, 메소드는 프로토타입에서 정의합니다. 생성자에는 속성에 대한 정의만 있으며 메소드는 별도의 블럭으로 구분할 수 있으니 코드를 읽기가 훨씬 쉬워집니다.

// 생성자에서 속성 정의
function Test(a, b, c, d) {
  // 속성 정의
}

// 첫 메소드 정의
Test.prototype.x = function() { ... };

// 두번째 메소드 정의
Test.prototype.y = function() { ... };

// 그 외.

Object-oriented programming

Classes and instances