생성자 함수

soyeon·2022년 9월 19일
0

TIL

목록 보기
21/32

https://youtu.be/8hrSkOihmBI
https://ko.javascript.info/constructor-new

코딩앙마님의 자바스크립트 중급 강좌 + 코어 자바스크립트를 보고 정리한 글입니다.

생성자 함수

  • 같은 객체를 여러개 만들어야할 때 new연산자와 생성자 함수를 사용한다.
  • 첫글자를 대문자로 하는 게 관례
  • 변수에 객체를 할당하면 this는 해당 변수가 됨.
function User(name,age){
  this.name = name;
  this.age = age;
  this.sayName = function() {
  	console.log(this.name);
  }
}

//this === user5
let user5 = new User('Han',40);

user5.sayName(); // 'Han'

생성자 함수의 원리

function User(name,age){
  // this = {} 빈 객체가 자동으로 만들어짐

  // 새로운 프로퍼티를 this에 추가
  this.name = name;
  this.age = age;
  this.sayName = function() {
  	console.log(this.name);
    
  // return this; (this가 자동으로 반환됨)
  }
}

return 문을 쓴다면..?

  • 생성자 함수는 자동으로 this가 리턴되기 때문에 쓸 필요가 없음
  • 객체를 return하는 코드를 작성한 경우 this 대신 객체가 반환됨
  • 이 외의 경우에는 this가 반환됨
function BigUser() {
  this.name="원숭이";
  
  return {name:"고릴라"}; // this가 아닌 객체가 반환됨
}

alert(new BigUser().name); //고릴라

function SmallUser() {
  this.name = "원숭이";
  return; // this를 반환함
}
alert(new SmallUser().name); //원숭이

new function()

  • 단 한번만 호출할 목적 (재사용 불가)
  • 코드를 캡슐화하기 위해 사용
let user = new function() {
  this.name = 'sans';
  this.age = '26';
  .
  .
  .
  //졸라 복잡한 코드들
}

퀴즈 푼 거 09.23

계산기 만들기

아래와 같은 세 개의 메서드를 가진 생성자 함수, Calculator를 만들어보세요.

  • read() – prompt 함수를 이용해 사용자로부터 값 두 개를 받고, 이를 객체 프로퍼티에 저장합니다.
  • sum() – 프로퍼티에 저장된 값 두 개를 더한 후 반환합니다.
  • mul() – 프로퍼티에 저장된 값 두 개를 곱한 후 반환합니다.
function Calculator() {
  this.a;
  this.b;
  this.read = () => {
    this.a = Number(window.prompt("첫번째 숫자를 입력하세요"));
    this.b = Number(window.prompt("두번째 숫자를 입력하세요"));
  };
  this.sum = () => {
    return this.a + this.b;
  };
  this.mul = () => {
    return this.a * this.b;
  };
}

누산기 퀴즈 09.24

누산기 만들기

Accumulator(startingValue)를 이용해 만드는 객체는 아래와 같은 요건을 충족해야 합니다.

  • 프로퍼티 value에 현재 값(current value)을 저장합니다. 최초 호출 시엔 생성자 함수의 인수, startingValue에서 시작값(starting value)을 받아옵니다.
  • 메서드 read()에선 prompt 함수를 사용해 사용자로부터 숫자를 받아오고, 받은 숫자를 value에 더해줍니다.
    프로퍼티 value엔 startingValue와 사용자가 입력한 모든 값의 총합이 더해져 저장됩니다.
function Accumulator(num) {
  this.value = num;
  this.sum = 0;
  this.read = () => {
    this.sum = Number(window.prompt("숫자를 입력하세요."));
    this.value += this.sum;
  };
}

let accumulator = new Accumulator(1);

accumulator.read(); // 사용자가 입력한 값을 더해줌
accumulator.read(); // 사용자가 입력한 값을 더해줌

alert(accumulator.value);
profile
공부중

0개의 댓글