개발일지
article thumbnail
Published 2023. 4. 11. 00:25
JavaScript.info 프로그래밍/JavaScript

JavaScript.info

자바스크립트는 매우 인기있는 프로그래밍 언어입니다. 이 언어를 사용하면 브라우저에서 실행되는 다양한 기능을 만들 수 있으며, 최근에는 서버 측 개발에도 많이 사용됩니다. 이번 블로그에서는 자바스크립트의 기본 개념인 변수, 함수, 객체, 프로토타입, 클래스, 프라미스 및 async/await에 대해 알아보겠습니다.


자바스크립트 기본


 #변수와 상수

자바스크립트에서 변수는 var, let, const 키워드로 선언할 수 있습니다. var 키워드는 ES2015 이후 더 이상 권장되지 않습니다. let은 값을 변경할 수 있는 변수를, const는 값을 변경할 수 없는 상수를 선언합니다.

let myVariable = 'Hello World';
const myConstant = 42;

#함수와 함수 표현식, 화살표 함수

자바스크립트에서 함수는 function 키워드를 사용하여 선언할 수 있습니다. 함수는 매개변수를 받아서 처리하고 결과를 반환할 수 있습니다. 함수 표현식은 변수에 함수를 할당하는 것입니다. 화살표 함수는 더 간단한 문법으로 함수를 선언할 수 있습니다.

// 함수 선언문
function myFunction(parameter1, parameter2) {
  return parameter1 + parameter2;
}

// 함수 표현식
const myFunction = function(parameter1, parameter2) {
  return parameter1 + parameter2;
}

// 화살표 함수
const myFunction = (parameter1, parameter2) => parameter1 + parameter2;

객체


#객체와 참조에 의한 객체 복사

자바스크립트에서 객체는 중괄호 {}로 만들 수 있습니다. 객체는 속성과 값으로 이루어져 있으며, 객체의 속성은 점(.) 또는 대괄호([ ])를 사용하여 접근할 수 있습니다. 객체는 참조에 의해 복사되며, 이는 객체를 다른 변수에 할당하면 객체의 참조가 복사된다는 것을 의미합니다.

const myObject = { name: 'John', age: 30 };
const myOtherObject = myObject; // 참조에 의한 복사

myObject.name = 'Jane';
console.log(myOtherObject.name); // 'Jane'

#가비지 컬렉션

자바스크립트는 가비지 컬렉션을 통해 메모리를 관리합니다. 가비지 컬렉션은 사용하지 않는 메모리를 자동으로 해제하는 것을 말합니다.


#메서드와 this

객체의 메서드는 객체 내에서 함수로 정의된 속성입니다. 메서드 내부에서 this 키워드를 사용하면 현재 객체를 참조할 수 있습니다.

const myObject = {
  name: 'John',
  age: 30,
  sayHello: function() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
};

myObject.sayHello(); // 'Hello, my name is John and I am 30 years old.'

#new 연산자와 생성자 함수

new 연산자를 사용하여 생성자 함수를 호출하면 객체를 만들 수 있습니다. 생성자 함수는 함수이며, 첫 글자를 대문자로 쓰는 것이 관례입니다.

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

const john = new Person('John', 30);
console.log(john.name); // 'John'

객체 프로퍼티 설정


#프로퍼티 getter와 setter

객체의 속성을 설정할 때 get과 set 키워드를 사용할 수 있습니다. 이를 통해 속성에 대한 값을 설정하거나 가져올 때 추가적인 로직을 수행할 수 있습니다.

const myObject = {
  _name: 'John',
  get name() {
    return this._name.toUpperCase();
  },
  set name(newName) {
    this._name = newName;
  }
};

myObject.name = 'Jane';
console.log(myObject.name); // 'JANE'

 


프로토타입과 프로토타입 상속


#프로토타입 상속

자바스크립트에서 모든 객체는 프로토타입이라는 객체를 가집니다. 이를 통해 프로토타입 체인을 통해 객체 간에 상속을 구현할 수 있습니다.

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

function Student(name, age, grade) {
  Person.call(this, name, age);
  this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

const john = new Student('John', 15, '9th');
john.sayHello(); // 'Hello, my name is John and I am 15 years old.'

클래스


#클래스와 기본 문법, 클래스 상속

ES6부터는 클래스 문법이 추가되었습니다. 클래스는 생성자 함수와 유사한 기능을 제공하며, 클래스 상속을 사용하여 상속을 구현할 수 있습니다.

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

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

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }
}

const john = new Student('John', 15, '9th');
john.sayHello(); // 'Hello, my name is John and I am 15 years old.'
``

프라미스와 async, await


#콜백, 프라미스, 프라미스 체이닝

비동기 작업을 처리할 때 콜백 함수를 사용하는 것은 콜백 지옥을 일으킬 수 있습니다. ES6부터는 프라미스와 async, await를 사용하여 비동기 작업을 보다 간편하게 처리할 수 있습니다.

function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = [1, 2, 3, 4, 5];
      if (data) {
        resolve(data);
      } else {
        reject('Error');
      }
    }, 1000);
  });
}

async function printData() {
  try {
    const data = await getData();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

printData();

위 예제에서는 getData 함수가 프라미스를 반환하며, 프라미스가 완료될 때까지 1초를 대기합니다. 이후 async 함수인 printData에서 await 키워드를 사용하여 getData 함수의 완료를 대기하고, 데이터를 출력합니다. 만약 getData 함수가 에러를 반환한다면 catch 블록에서 에러를 처리합니다.


마무리

이상으로 자바스크립트의 기본적인 개념과 객체, 클래스, 프라미스와 async, await 등에 대해 살펴보았습니다. 이외에도 자바스크립트에는 많은 개념과 기능이 있으며, 이를 다룰 수 있는 다양한 자료들이 있습니다. 더 많은 학습을 통해 높은 수준의 자바스크립트 개발자가 되시길 바랍니다!

 
profile

개발일지

@damin06

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!