/ FRONTEND

클린코드 자바스크립트 7-1 함수 다루기([함수,메서드,생성자], argument & parameter,복잡한 인자 관리하기)

Clean Code JS 강좌는 여러 절로 구성되어 있습니다.

함수 다루기 😎

함수, 메서드, 생성자👍

1급 객체

  • 변수나, 데이터에 담길 수 있다.
  • 매개변수로 전달 가능 (콜백 함수)
  • 함수가 함수를 반환 (고차 함수)
function func() {
  return this;
}

// 객체 메서드
const obj = {
  conciseMethod() {
    return this;
  },
};

// 생성자 함수 (Class)
function Func() {
  return this;
}

// 전역을 바라본다
func();

// 메서드 => 객체에 의존성이 있는 함수, OOP 행동을 의미
obj.method();

//생성자 함수 => 인스턴스를 생성하는 역할 => Class
const instance = new Func();

argument & parameter👍

  1. Parameter (Formal Parameter) : 형식을 갖춘, 매개변수
  2. Arguments (Actual Parameter) : 실제로 사용되는, 인자
function axios(url) {
  // Parameter
  // some code...
}

axios("https://github.com"); //Arguments

복잡한 인자 관리하기👍

  • 무조건 3개 이상이 나쁜게 아니다.
  • 맥락을 파악할 수 있으면 된다.
function toggleDisplay(isToggle) {
  // ..some code
}

function sum(sum1, sum2) {
  // ..some code
}
sum(1, 2);
function getRandomNumber(min, max) {
  // ..some code
}

function timer(start, stop, end) {
  // ..some code
}

function getSquare(top, right, bottom, left) {
  // ..some code
}
function createCar1(name, brand, color, type) {
  return {
    name,
    brand,
    color,
    type,
  };
}

// 객체 이용
function createCar2(options) {
  var name = options.name;
  var brand = options.brand;
  var color = options.color;
  var type = options.type;

  return {
    name: name,
    brand: brand,
    color: color,
    type: type,
  };
}

// 객체 구조 분해 할당
function createCar3({ name, brand, type, color }) {
  return {
    name,
    brand,
    color,
    type,
  };
}

function createCar4(name, { brand, type, color }) {
  return {
    name,
    brand,
    color,
    type,
  };
}

createCar4("차량 이름", {
  /*...somecode*/
});
  • 에러를 띄어주는 인자관리방법
function createCar({ name, brand, type, color }) {
  if (!name) {
    throw new Error("name is a required");
  }
  if (!brand) {
    throw new Error("brand is a required");
  }
}