Skip to content

Instantly share code, notes, and snippets.

@jinsangYoo
Last active January 18, 2019 01:46
Show Gist options
  • Save jinsangYoo/7c5a92257d127f070c4d9e6fae344df4 to your computer and use it in GitHub Desktop.
Save jinsangYoo/7c5a92257d127f070c4d9e6fae344df4 to your computer and use it in GitHub Desktop.
자바스크립트 생성자 함수

개요

  • javascript 재학습하면서 잊고 있던것, 긴가민가 했던것 재학습하면서 기록

생성자 함수

  • new 키워드로 객체를 생성할 수 있는 함수를 의미

생성자 함수 만들기

  • 생성자는 대문자로 시작
  • Student() 함수를 new 키워드로 객체를 생성하므로 생성자 함수라고 알수 있음
    • new 키워드를 사용하지 않으면 함수 내부에서 this 키워드는 window를 가리킴
    • new 키워드를 사용하면 객체를 위한 공간을 만들고 this 키워드는 해당 공간을 의미하게 됨
function Student() { }

var student = new Student();
  • 생성자 함수 안에서는 this 키워드를 통해 생성자 함수로 생성될 객체의 속성을 지정
function Student(name, korean, math, english, science) {
  this.name = name;
  this.korean = korean;
  this.math = math;
  this.english = english;
  this.science = science;
  this.getSum = function() {
    return this.국어 + this.수학 + this.영어 + this.과학;
  };
  this.getAverage = function() {
    return this.getSum() / 4;
  };
  this.toString = function() {
    return this.이름 + '\t' + this.getSum() + '\t' + this.getAverage() + '\n';
  };
}

var student = new Student('응5', 97, 45, 56, 25);

instanceof

  • 해당 객체가 어떠한 생성자 함수로 생성됐는지 확인할 때 사용
var student = new Student('응5', 97, 45, 56, 25);
console.log("student: " + JSON.stringify(student));
// student instanceof Student: true
console.log("student instanceof Student: " + String(student instanceof Student));
// student instanceof Number: false
console.log("student instanceof Number: " + String(student instanceof Number));
// student instanceof String: false
console.log("student instanceof String: " + String(student instanceof String));
// student instanceof Boolean: false
console.log("student instanceof Boolean: " + String(student instanceof Boolean));

프로토타입

  • 생성자 함수로 생성된 객체가 공통으로 가지는 공간
function Student(name, korean, math, english, science) {
  this.name = name;
  this.korean = korean;
  this.math = math;
  this.english = english;
  this.science = science;
}
Student.prototype.getSum = function() {
  return this.korean + this.math + this.english + this.science;
};
Student.prototype.getAverage = function() {
  return this.getSum() / 4;
};
Student.prototype.toString = function() {
  return this.name + '\t' + this.getSum() + '\t' + this.getAverage() + '\n';
};

var student = new Student('응5', 97, 45, 56, 25);
// student: {"name":"응5","korean":97,"math":45,"english":56,"science":25}
console.log("student: " + JSON.stringify(student));
// student.toString(): 응5	223	55.75
console.log("student.toString(): " + student.toString());

캡슐화

  • 외부에서 n에 직접 접근하지 못하도록 숨김
  • getN() 통해서만 n에 접근 가능
function Student(name, korean, math, english, science) {
  var n = name + '!!!';
  this.name = name;
  this.getN = function () {
      return n;
  }
}

var student = new Student('응5', 97, 45, 56, 25);
console.log("student: " + JSON.stringify(student));
console.log("student.n: " + student.n);
console.log("student.getN(): " + student.getN());

상속

  • ECMAScript 5
function Rectangle(w, h) {
  var width = w;
  var height = h;

  this.getWidth = function() {
    return width;
  };

  this.getHeight = function() {
    return height;
  };

  this.setWidth = function (w) {
    if (w < 0) {
      throw '길이는 음수 no';
    }
    else {
      width = w;
    }
  };

  this.setHeight = function (h) {
    if (h < 0) {
      throw '높이는 음수 no';
    }
    else {
      height = h;
    }
  };
}

Rectangle.prototype.getArea = function () {
  return this.getWidth() * this.getHeight();
};

function Square(length) {
  // Rectangle 객체의 속성을 Square 객체에 추가
  this.base = Rectangle;
  // 꼭 base 라고 명명할 필요는 없음
  this.base(length, length);
}
// Rectangle 객체의 프로토타입이 가진 속성 또는 메서드를 Square 객체의 프로토타입에 복사
Square.prototype = Rectangle.prototype;
Square.prototype.constructor = Square;

var rectangle = new Rectangle(5, 7);
var square = new Square(5);
console.log(rectangle.getArea() + ': ' + square.getArea());
console.log("square instanceof Rectangle: " + String(square instanceof Rectangle));
  • 생성자 함수 Square의 프로토타입 constructor() 메서드에 Square를 다시 넣는 부분이 없어도 정상작동함
    • 하지만, 직접 square 객체의 constructor() 메서드를 출력해보면 생성자 함수 Square가 아니라 생성자 함수 Rectangle을 가리킴
    • 따라서 프로토 타입의 생성자 함수를 재정의 한것

// Square.prototype.constructor = Square

Square.prototype.constructor
ƒ Rectangle(w, h) {
  console.log("constructor in Rectangle");
  var width = w;
  var height = h;

  this.getWidth = function() {
    return width;
  };

  this.getHeight = 
}

Square.prototype.constructor = Square

Square.prototype.constructor
ƒ Square(length) {
  console.log("constructor in Square");
  this.base = Rectangle;
  this.base(length, length);
}
  • ECMAScript 6
    • 클래스 기반의 객체지향 언어 이념을 도입
    • class 키워드 도입
    • 생성자 함수를 constructor 함수가 처리
    • 메서드 선언을 프로토타입 안에 선언하는 것이 아니라 class 블록 내부에 선언
    • 게터, 세터 작성 방법 변경
      • get을 붙여 만든 메서드는 값을 가져오는 행위를 할 때 자동으로 호출
      • set을 붙여 만든 메소드는 값을 넣는 행위를 할 때 자동으로 호출
      • 기존 생성자 함수로 게터, 세터 구현할 때 보다 간단
      • 2017년 4월 기준 게터, 세터를 사용하면 스택 추적(오류 확인)이 어렵고, 유지 보수가 어렵고, 메서드 체이닝에 활용하기 힘들다는 이유로 사용 자제
      • 예시
        • get width() { ... }
        • set width(input) { ... }
    • ECMAScript 6의 클래스는 변수를 숨길 수 없음
      • 절대 개발한 나 말고 만지지 말아 주세요라는 의미를 나타낼때 변수 앞에 '_'를 붙임
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment