본문 바로가기

Front/Java Script

객체의 생성 ( 생성자 & new )

 

 

객체의 생성

 

var person = {
      'name' : 'bolbbang',
      'introduce' : function(){
                             return `my name is ${this.name}`;
                          }
}
document.write(person.introduce());

//person.name = 'bolbbang' 으로 객체의 프로퍼티를 넣을 수 있지만, 객체를 정의하는 부분이 분산되므로 위와 같이 사용하는 것이 좋다.

 

 

 

 

 

new  ( 생성자 함수를 이용하여 객체 생성하기 )

 

function Person(){}   // Person이라는 기본 함수 정의

var p0 = Person();    // p0 = undefined
var p1 = new Person();    // p1 = {}    // 함수에 new를 붙이면 그 return 값은 객체가 된다. 이때의 함수는 생성자라고 한다.

 

 

 

 

function Person(name){
  this.name = name;
  this.introduce = function(){
       return `my name is ${this.name}`;
  }
}

var p1 = new Person('bolbbang');
document.write(p1.introduce());      // 결과 : my name is bolbbang
var p2 = new Person('green');
document.write(p2.introduce());     // 결과 : my name is green

 

===> 생성자가 하는 일

 객체의 초기화.

객체가 생성될 때, 어떤 프로퍼티와 어떤 메소드를 가지고 있을 지를 미리 세팅해놓음.

 

*** 생성자 함수는 단순히 프로퍼티와 메소드를 정의한다. 아무것도 리턴하지않고, 객체를 만들지도 않는다.


생성자 테스트 해보기

 

function Func(){
   this.f = function(){
      console.log('hello');
    }
}

var o1 = new Func();
var o2 = new Func();
console.log(o1 === o2);    // false
console.log(o1.f === o2.f)   // false

 

 

 

 

 

출처

opentutorials.org/course/743/6570

'Front > Java Script' 카테고리의 다른 글

상속 (prototype)  (0) 2021.04.29
전역객체 / this & this의 제어  (0) 2021.04.20
함수의 호출(call & apply)  (0) 2021.04.20
arguments VS parameter  (0) 2021.04.20
클로저(closure)  (0) 2021.04.12