241030 함수

수달·2024년 10월 30일

함수

1.1 즉시 실행 함수 (IIFE)

  • 전역 범위를 오염시키지 않고 싶을 때 사용함
(function greet() {
  console.log("Hello");
})();

2. 생성자 함수

  • 함수로 객체를 정의하는 방법
function user() {
  this.name = "철수";
  this.age = 30;
}

const userObj = {
  name: "철수",
  age: 30,
};
console.log(userObj);

const u = new user();
console.log(u);
  • 생성자 함수로 구별되기 위해 파스칼 케이스 사용
function User() {
  this.name = "철수";
  this.age = 30;
}

const u = new User();
console.log(u);
function Car() {
  this.name = "bmw";
  this.color = "white";
}

const car1 = new Car();
const car2 = new Car();
const car3 = new Car();

console.log(car1.name);
console.log(car1.color);
function Car(name, color) {
  this.name = name;
  this.color = color;
}

const car1 = new Car("benz", "white");

console.log(car1.name);
console.log(car1.color);

const car2 = new Car("bmw", "black");

console.log(car2.name);
console.log(car2.color);

2.1 인스턴스

  • 생성자 함수: 객체를 찍어내는 함수
    객체 원하는 모양을 만들어 낼 수 있음
  • 인스턴스: 생성자 함수로 만들어 낸 객체
// 생성자 함수
function Car(name, color) {
  this.name = name;
  this.color = color;
  this.getInfo = function () {
    return `${this.name}, ${this.color}`
  };
}

// 인스턴스: 생성자 함수로 만들어 낸 객체
const car1 = new Car("benz", "white");

console.log(car1.name);
console.log(car1.color);

3. 프로토타입

  • 함수와 일대일로 매칭되는 공간
  • 모든 함수마다 1개씩 있음
  • 숨어있음
Car.prototype.type = "Vehicle";
Car.prototype.getInfo = function () {
  return `${this.name}, ${this.color}`;
};

4. 프로토타입 체인

  • 인스턴스가 프로토타입 객체를 탐색해 나가는 과정

function Car(name, color) {
  this.name = name;
  this.color = color;
}

// 프로토타입
Car.prototype.getInfo = function () {
  return `${this.name}, ${this.color}`;
};

const car1 = new Car("benz", "white");
console.dir(car1);
// 프로토타입의 히든 객체
console.dir(car1.__proto__);
console.dir(car1.name);
console.dir(car1.color);
console.dir(car1.getInfo());
console.dir(car1.__proto__.getInfo());

const car2 = new Car("bmw", "black");
console.dir(car2);
  • 값이 변하지 않고 공통적으로 사용되는 속성은 프로토타입 객체에
  • 그게 아니면 생성자 함수 내부에
const userObj = {
  name: "철수",
  age: 20,
};

console.dir(userObj);
console.log(userObj.hasOwnProperty("name"));
  • __proto__ : 상위 프로토타입 객체

래퍼 객체 (wrapper object)

  • 자바스크립트 엔진이 기본 자요형의 값을 객체처럼 사용하기 위해서 암묵적으로 만드는 객체
  • 그 자료형과 관련있는 생성자 함수의 인스턴스 객체로 감싸요.
  • 숫자다? Number() 생성자 함수로부터 내가 객체를 만든 다음에 널 감싸줄게

1)

const PI = 3.14159265;
console.dir(PI);
console.log(PI.toFixed(2));

function Calculator() {}
Calculator.prototype.add = function (a, b) {
  return a + b;
};
Calculator.prototype.subtact = function (a, b) {
  return a - b;
};
Calculator.prototype.multiply = function (a, b) {
  return a * b;
};

const instance = new Calculator();
console.dir(instance);
console.log(instance.add(10, 2));
console.log(instance.subtact(10, 2));

2)

function Counter() {
    this.count = 0;
}

Counter.prototype.increment = function () {
    this.count++;
};

Counter.prototype.decrement = function () {
    this.count--;
};

Counter.prototype.getCount = function () {
    return this.count;
};

const counter = new Counter();
counter.count = 100;
console.log(counter.getCount());

4.2 고급 패턴 중

4.2.1 프라이빗하게 사용하는 방법

원래 코드

function BankAccount(initialBalance) {
  this.balance = initialBalance;
}
BankAccount.prototype.deposit = function (amount) {
  this.balance += amount;
};
BankAccount.prototype.withdraw = function (amount) {
  this.balance -= amount;
};

const woori = new BankAccount(1000);
woori.deposit(2000);
woori.balance = 10000000;
console.log(woori.balance);

바꾼 코드

function BankAccount(initialBalance) {
  let balance = initialBalance;

  this.deposit = function (amount) {
    balance += amount;
  };
  this.withdraw = function (amount) {
    balance -= amount;
  };

  this.getBalance = function () {
    return balance;
  };
}

const woori = new BankAccount(1000);
woori.deposit(2000);
woori.balance = 10000000;
console.log(woori.balance);
console.log(woori.getBalance());

4.2.2 생성자 함수 팩토리 패턴

function createPerson(type) {
  function Employee(name) {
    this.name = name;
    this.type = "employee";
  }
  function Manager(name) {
    this.name = name;
    this.type = "manager";
  }

  switch (type) {
    case "employee":
      return new Employee(name);
    case "manager":
      return new Manager(name);
  }
}

4.2.3 상속

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

Person.prototype.introduce = function () {
  return `I am ${this.name}`;
};

function Developer(name, position) {
  Person.call(this, name); // Person 땡겨옴
  // this.name = name;
  this.position = position;
}

// 프로토타입
Developer.prototype = Object.create(Person.prototype);
Developer.prototype.constructor = Developer;
Developer.prototype.skill = function () {
  // return `react.js`;
  return this.position;
};

const dev = new Developer("철수", "프론트 개발자");
console.dir(dev.introduce());
console.dir(dev.skill());

0개의 댓글