생성자 constructor

PYG·2021년 5월 18일

OOP

목록 보기
4/8

생성자 constructor

  • new 생성자

1.1

function Person(){
    this.name = 'park';
    this.first = 50;
    this.second = 30;
    this.third = 20;
    this.sum = function(){
        return this.first + this.second + this.third;
    }
}
console.log(Person());
console.log(new Person());
    1. 단지 함수일 뿐 - undefined
    1. Person이라는 함수 객체가 생성
      Person {
      name: 'park',
      first: 50,
      second: 30,
      third: 20,
      sum: [Function (anonymous)]
      }

1.2

  • 중괄호'{}' 즉 객체를 만들 때마다 그 객체를 다시 정의를 해줘야 하는데 앞에 new를 사용한 생성자 function을 만들게 되면 이 생성자 function과 연결하고자 하는 모든 객체들이 연결된다
function Person(){
    this.name = 'park';
    this.first = 50;
    this.second = 30;
    this.third = 20;
    this.sum = function(){
        return this.first + this.second + this.third;
    }
}
var student1 = new Person();
var student2 = new Person();
  • 이렇게 하면 student1과 student2는 같은 값이 나온다

1.3

  • 생성자 function의 내용만 바꾸면 생성자 function에 의해 만들어진 모든 객체의 내용이 한 번에 바뀐다
function Person(name, first, second, third){
    this.name = name;
    this.first = first;
    this.second = second;
    this.third = third;
    this.sum = function(){
        return this.first + this.second + this.third;
    }
}
var student1 = new Person('park', 20, 30, 40);
var student2 = new Person('lee', 30, 40, 10);
console.log(student1.sum());
console.log(student2.sum());
  • 값은 90, 80이 나온다

0개의 댓글