Constructor

constructor는 비슷한 object를 만들기 위해 사용한다.

var people = {name:'kim'}
var people2 = {name:'kim'}
var people3 = {name:'kim'}

이렇게 만들면 비효율적이다.

var student = {name: 'Kim', age: 15}

function Constructor(){
  this.name = 'Kim';
  this.age = 15;
}

var student1 = new Constructor();
var student2 = new Constructor();

student1, student2 라는 object가 생성된다.

반복문으로 만들 수도 있다.

object내부에 함수도 추가.

// 이런 object를 만들어보자.
var student = {
  name: 'Kim', 
  age: 15,
  sayHi : function(){
    console.log('hello, myname is ' + this.name);
  }
}


function Constructor(){
  this.name = 'Kim';
  this.age = 15;
  this.sayHi = function(){
    console.log('hello, myname is ' + this.name);
  }
}

var student1 = new Constructor();
var student2 = new Constructor();

이제 내부에 있는 내용들이 다르게 만들어보자.

function Constructor(name, age){
  this.name = name;
  this.age = age;
  this.sayHi = function(){
    console.log('hello, myname is ' + this.name);
  }
}

var student1 = new Constructor('kim', 15);
var student2 = new Constructor('lee', 17);