JavaScript 기초-03

wonder1ng·2025년 2월 7일

풀스택 기초

목록 보기
7/13

07 함수

  • 함수: 코드의 집합. 코드를 저장하여 호출하여 사용.
    • 선언적 함수(function 함수명): 호이스팅되어 함수 선언 위치 사용 없이 사용 가능
    • 익명 함수(함수명 = function): 호이스팅되지 않아 함수 선언 후에 사용 가능
    • 콜백 함수: 매개 변수로 전달하는 함수. 비동기 처리로 기계어 번역 시관과 처리 시간이 다름.
  • 매개 변수, 인자(parameter): 함수가 받아 사용하도록 미리 선언된 변수
  • 인수(argument): 함수(인자)에게 전달한 값
  • 리턴값(return): 함수가 내놓은 값(출력은 리턴값이 아님)
  • 가변 매개 변수(...): 배열을 전개해서 전달하거나 받음.
    • arguments: 구버전 가변 매개변수
  • 기본 매개 변수(param=value): 인자에서 기본(인수 미 입력 시 사용)으로 설정된 인수

07-01 선언적 함수와 익명 함수

  • function: 함수 선언의 기본형. 메서드에서 this가 함수(자신) 객체를 가리킴.
  • () => {}(화살표 함수): 간단한 함수 선언. 메서드에서 this가 전역 객체를 가리킴.
  • return: 함수 결과 반환
//4가지 형식
// 1. 매배변수 X 반환값 X
function myFunc1() {
  console.log("myFunc1()");
}
myFunc1();

// 2. 매개변수 O 반환값 X
function myFunc2(param) {
  console.log("myFunc2()" + param);
  return; // `return;`: myFunc1처럼 안 적어도 됨
}
// 여기서 param이 인자, "홍길동"이 인수
myFunc2("홍길동");

// 3. 매개변수 X 반환값 O
function myFunc3() {
  return "홍길동2";
}
const name = myFunc3();
console.log(name);

// 4. 매개변수 O 반환값 O
function myFunc4(param) {
  return param * 2;
}
console.log(myFunc4(2));

// 함수형 변수(익명함수)
let varFunc = function () {
  console.log("varfunc()");
  return;
};
varFunc();
// 선언 함수 익명 함수 비교
console.log(typeof myFunc1, typeof varFunc);
console.log(myFunc1);
console.log(varFunc);

// 화살표 연산자 사용
let varFunc2 = () => {
  console.log("varfunc2()");
  return;
};
varFunc2();

// 전개 연산자 사용
let reduceSum = (...arr) => {
  res = 0;
  console.log(typeof arr, arr);
  for (let i of arr) {
    res += i;
  }
  return res;
}
console.log(reduceSum(1, 2, 3, 4, 5));
// arguments: 구버전 가변 매개변수. 화살표 함수 사용 불가.
let argumentsSum = function() {
  res = 0;
  arguments;
  console.log(typeof arguments, arguments);
  for (let i of arguments) {
    res += i;
  }
  return res;
}
console.log(argumentsSum(1, 2, 3, 4, 5));

// 기본 매개 변수
let greeting = (name="아무개") => {
  console.log(name + "님 반갑습니다.");
}
greeting();
greeting("홍길동");
// 구버전 코드
let oldGreeting1 = (name) => {
  name = name !== undefined ? name : "아무개";
  console.log(name + "님 반갑습니다.");
}
oldGreeting1();
oldGreeting1("홍길동");
let oldGreeting2 = (name) => {
  name = name || "아무개";
  console.log(name + "님 반갑습니다.");
}
oldGreeting2();
oldGreeting2("홍길동");

07-02 콜백 함수

  • Array.forEach((value) => {}): 배열의 원소를 인수로 받는 콜백 함수
  • Array.map((value, index, array) => {}): value, index, array를 인수로 받아 함수 실행
  • Array.filter((value, index, array) => {}): value, index, array를 인수로 받아 조건에 따른 true 값만 반환
  • Array.reduce((previousValue, currentValue, index, array) => {}, firstValue}: previousValue, currentValue, index, array를 인수로 받아 함수 실행. 최초의 previousValue = firstValue
  • Array.find((value, index, array) => {return condition}): value, index, array를 인수로 받아 condition이 true일 때 value 반환
// 콜백 함수
let sum = (param1, param2) => {
  return param1 + param2;
};
let sub = (param1, param2) => {
  return param1, param2;
};
function calc(param1, param2, method) {
  return method(param1, param2);
}
console.log(calc(10, 20, sum));
console.log(calc(10, 20, sub));

// Array.forEach()
let arr = [10, 20, 30, 40, 50];
arr.forEach((element) => {
  // `arr.forEach((element) => {`: 인자에 괄호 없어도 작동동
  console.log(element + 5);
});
console.log(arr);
// Array.map(value, index, array)
arr.map((value, index, array) => {
  console.log(value, index, array);
});
console.log(
  arr.map((v) => {
    return v * v;
  })
);
// Array.filter(value, index, array)
let filterArr = arr.filter((v) => {
  return parseInt(v / 10) % 2 === 0;
});
console.log(filterArr);
// Array.reduce((previousValue, currentValue, index, array) => {}, firstValue}
const nums = [10, 20, 30, 40, 50];
var reduceSum = nums.reduce((pre, cur) => {
  console.log(pre, cur); // 10 20, 30, 30, 60 40, 100, 50
  return pre + cur;
});
console.log(reduceSum);
reduceSum = nums.reduce((pre, cur, index, arr) => {
  console.log(pre, cur, index, arr); // 0 10 0, 10 20 1, 30 30 2
  return pre + cur;
}, 0); // 두번째 인자에 pre의 초기값을 준다
console.log(reduceSum);
// 알파벳 갯수 구하기
const alphabets = ["a", "a", "c", "c", "c"];
// 결과값 {a: 2, c:3}
let count = alphabets.reduce((acc, cur) => {
  // acc = {}, cur = 'a'
  if (acc[cur]) {
    acc[cur] += 1;
    // {a: 2}
  } else {
    acc[cur] = 1; // acc['a'] = 1 => {a: 1}
  }
  return acc;
}, {});
console.log(count);
// find
let foundVal = nums.find((item, index, array) => {
  // return item < 10; // 못 찾으면 undefined
  return item < 35; // 10을 반환 후 종료
});
console.log(foundVal);

06-03 타이머

  • setTimeout: 지정 시간 후 작동
  • setInterval: 지정 시간 마다 작동
  • clearTimeout: setTimeout 함수 정지
  • clearInterval: setInterval 함수 정지
// timeout과 interval
setTimeout(() => {
  console.log("2초 후에 출력합니다.");
}, 2 * 1000); // 1000 = 1초

let interval = setInterval(() => {
  console.log("0.5초마 다 출력합니다.");
}, 1 * 500);

setTimeout(() => {
  console.log("interval을 종료합니다.");
  clearInterval(interval)
}, 3 * 1000 - 1);

let timeout = setTimeout(() => {
  console.log("3초 후에 출력합니다.");
}, 2 * 1000);

setTimeout(() => {
  console.log("timeout을 종료합니다.");
  clearTimeout(timeout)
}, 1 * 1000 - 1);

06-04 즉시 호출 함수

  • 즉시 호출 함수: 함수를 선언하자마자 즉시 실행함으로써 변수 충돌 방지 등을 위해 사용
// 즉시 호출 함수
(function() {
  console.log('이 함수는 즉시 호출됩니다!');
})();
(() => {
  console.log('이 함수는 즉시 호출됩니다!');
})();

06-05 this, call, apply, bind

  • this: 자기 자신을 가르키는 키워드
  • call: this와 인수들을 설정(ChatGPT 응답)
  • apply: this와 함께 인수를 배열로 전달(ChatGPT 응답)
  • bind: 즉시 실행되지 않고, 나중에 호출될 때 this와 인수들이 적용(ChatGPT 응답)
// 전체 코드는 ChatGPT 응답임.
// this
// 메서드
console.log("this 1번 메서드");
let obj1 = {
  fun1: function () {
    console.log(typeof this);
    console.log(this);
  },
  fun2: () => {
    console.log(typeof this);
    console.log(this);
  }
}
obj1.fun1(), obj1.fun2();

// 함수
console.log("this 2번 함수");
(function ()  {
  console.log(typeof this);
  console.log(this);
  (function () {
    console.log(typeof this);
    console.log(this);
  })();
  (() => {
    console.log(typeof this);
    console.log(this);
  })();
})();

// call, apply, bind(ChatGPT 응답)
const person = { name: 'Alice' };

function greetCall(city, country) {
  console.log(`Hello, I'm ${this.name}, from ${city}, ${country}`);
}
// call을 사용하여 this를 person 객체로 설정하고, 인수들은 직접 전달
greetCall.call(person, 'New York', 'USA'); 

function greetApply(city, country) {
  console.log(`Hello, I'm ${this.name}, from ${city}, ${country}`);
}
// apply를 사용하여 this를 person 객체로 설정하고, 인수들을 배열로 전달
greetApply.apply(person, ['New York', 'USA']); 

function greetBind(city, country) {
  console.log(`Hello, I'm ${this.name}, from ${city}, ${country}`);
}
// bind를 사용하여 this를 person 객체로 설정하고, 인수들을 고정
const greetPerson = greetBind.bind(person, 'New York');
// greetPerson 함수는 나중에 호출될 때 'New York'과 다른 인수를 전달할 수 있음
greetPerson('USA'); 
  • 요약(ChatGPT 응답)
메서드설명this 설정 방법인수 전달 방법반환값예제
call함수를 즉시 호출하며 this와 인수를 지정첫 번째 인수로 this를 설정나머지 인수들을 개별적으로 전달함수의 실행 결과greet.call(person, 'New York', 'USA')
apply함수를 즉시 호출하며 this와 인수를 배열 형태로 지정첫 번째 인수로 this를 설정두 번째 인수로 배열을 전달함수의 실행 결과greet.apply(person, ['New York', 'USA'])
bind새로운 함수를 반환하며, this와 일부 인수를 고정해둔 채 반환첫 번째 인수로 this를 설정고정된 인수들고정된 this와 인수로 실행할 새로운 함수const greetPerson = greet.bind(person)

08 Class

08-01 클래스 기본

  • 추상화: 필요한 요소만으로 객체를 표현하는 것
  • 프로토타입(prototype): 객체에 적은 지원하지만 제한도 적음
  • 클래스(class): 객체에 수많은 지원하지만 제한도 많음
  • 인스턴스(instance): 클래스 기반으로 만든 객체. 그냥 객체라고 부르기도 함.
  • 생성자(constructor): 인스턴스 생성 시 호출되는 메서드로 속성 추가나 객체 초기화 처리 등
// 클래스 선언
      class Student {
        // constructor(생성자): 인스턴스 생성 시 호출되는 메서드. 객체 초기화, 속성 추가 등
        constructor(name, kor, eng, math, sci) {
          this.name = name;
          this.kor = kor;
          this.eng = eng;
          this.math = math;
          this.sci = sci;
        }

        subjectsNum() {
          return Object.values(this).length - 1;
        }
        sum() {
          let res = 0;
          // prettier-ignore
          for (let score of Object.values(this).
          slice(1)) {
            res = res + score;
          }
          return res;
        }
        average() {
          return this.sum() / this.subjectsNum();
        }
        toString() {
          return `${
            this.name
          }\t${this.subjectsNum()} 과목\t${this.sum()}점\t${this.average()}점\n`;
        }
      }

      const students = [
        new Student("구름", 87, 98, 88, 90),
        new Student("별이", 92, 98, 96, 88),
        new Student("겨울", 76, 96, 94, 86),
        new Student("바다", 98, 52, 98, 92),
      ];

      for (let student of students) {
        console.log(student.toString());
      }

08-02 클래스 고급?

  • 상속(overriding): 부모 클래스의 기능을 자식 클래스가 물려 받는 것
    • override(오버라이드): 부모 함수를 자식에서 재선언하여 덮어쓰는 것.
  • private(#): 인스턴스 생성 후 속성이나 매서드를 수정 못 하게 함.
    • getter(게터)와 setter(세터): 사적(private) 속성에 접근하거나 할당할 수 있게하는 것으로 get[attr], set[attr]로 명명하거나 get과 set 키워드 사용.
  • static: 인스턴스 생성하지 않고 클래스로 바로 사용할 수 있는 정적 속성이나 정적 메서드 선언.
// 자식 클래스 선언
// extends: 상속 받을 부모 클래스 지정(다수 가능)
class MoreSubjects extends Student {
  #hist; // #: private 특성 적용
  #soc;
  static #counter = 0; // static: static 특성 적용
  constructor(name, kor, eng, math, sci, art, hist, soc) {
    // 사전에 잘못된 값 입력 못 하도록 예외 처리
    for (let score of [kor, eng, math, sci, art, hist, soc]) {
      if (score < 0 || score > 100 || parseInt(score) - score !== 0) {
        throw "인스턴스 생성 오류: 점수는 0 이상 100 이하의 정수여야 합니다.";
      }
    }
    // super: 부모 생성자 호출하는 함수
    super(name, kor, eng, math, sci);
    this.art = art;
    this.#hist = hist; // private 속성
    this.#soc = soc;
    // static 속성으로 this가 아닌 클래스명으로 접근
    MoreSubjects.#counter += 1;
  }

  // 부모 클래스와 동일한 메서드 재정의
  subjectsNum() {
    // super로 부모 메서드 접근 가능
    return super.subjectsNum() + 2; // 사적 속성 접근 불가로 #hist와 #soc는 따로 처리
  }
  sum() {
    return super.sum() + this.#hist + this.#soc;
  }

  // 게터
  getHist() {
    // 사적 속성도 클래스 내부에선 접근 가능
    return this.#hist;
  }
  // 세터
  setHist(value) {
    if (value < 0 || value > 100 || parseInt(value) - value !== 0) {
      throw "인스턴스 변경 오류: hist 점수는 0 이상 100 이하의 정수여야 합니다.";
    }
    this.#hist = value;
  }
  // get 키워드
  get soc() {
    // 사적 속성도 클래스 내부에선 접근 가능
    return this.#soc;
  }
  // set 키워드
  set soc(value) {
    if (value < 0 || value > 100 || parseInt(value) - value !== 0) {
      throw "인스턴스 변경 오류: soc 점수는 0 이상 100 이하의 정수여야 합니다.";
    }
    this.#soc = value;
  }

  // static
  static get counter() {
    return MoreSubjects.#counter + "명의 학생이 존재합니다.";
  }
}

const moreStudents = [
  new MoreSubjects("하늘", 91, 92, 85, 80, 50, 99, 80),
  new MoreSubjects("대지", 71, 99, 95, 90, 99, 81, 79),
];
for (let student of moreStudents) {
  // 따로 메서드 정의하지 않았지만 부모 클래스로부터 상속 받아 메서드 작동
  console.log(student.toString());
}

// private ==================================
try {
  let myError = new MoreSubjects("오류", 200, 99, 95, 86, 90, 81, 79);
} catch (error) {
  console.error(error);
}

let myError = new MoreSubjects("오류", 71, 99, 95, 86, 90, 81, 79);
try {
  for (key in myError) {
    myError[key] = 200;
    console.log(key + " 점수 변경 완료");
  }
  // 사적 속성은 접근 불가.
  console.log(Object.keys(myError));
  // hist라는 속성은 존재하지 않음
  console.log(myError.hist);
  // #soc에 접근 시 `SyntaxError: Private field '#soc' must be declared in an enclosing class` 발생
  // console.log(myError.#hist);
} catch (error) {
  console.error("인스턴스 생성 후 속성 접근 시 오류 미발생");
} finally {
  console.log(Object.entries(myError));
}

// getter & setter ======================================
// get[attr]: 게터
console.log(myError.getHist());
// set[attr]: 세터
myError.setHist(100);
console.log(myError.getHist());

try {
  console.log("soc 접근 가능: " + myError.soc);
  myError.soc = -1;
} catch (error) {
  console.error(error);
  myError.soc = 100;
  console.log("soc 재할당(게터 사용) 가능: " + myError.soc);
}

// static =========================================
console.log("static 속성 호출: " + MoreSubjects.counter);

출처: 한국경제신문 K-Digital Training - toss bank
첨고 서적:
윤인성 지음, 혼자 공부하는 자바스크립트, 한빛미디어, 2021년
고경희 지음, Do it! HTML+CSS+자바스크립트 웹 표준의 정석, 이지스퍼블리싱, 2024년

profile
데이터, 풀스택

0개의 댓글