[JS] 생성자와 new / this

다인·2022년 8월 8일
0

JavaScript

목록 보기
9/9

객체

객체 : 서로 연관된 변수와 함수를 그룹핑한 그릇
객체내의 변수 프로퍼티, 함수 메소드

var person = {
	'name': 'hello',
	'introduce': function(){
 	 	return 'My name is '+this.name;
	}
}

여러명을 만들 경우 -> 생성자와 new 사용해서 중복 제거

생성자 & new

: 객체를 만드는 역할을 하는 함수

// #1
function Person(){}
var p1 = new Person();  // 객체 생성
p1.name = 'hello';
p1.introduce = function(){
  return 'My name is '+this.name;
}

// #2
function Person(name){  //초기화
  this.name = name;
  this.introduce = function(){
  	return 'My name is '+this.name;
  }
}
var p1 = new Person('A');
var p2 = new Person('B');

console.log(p1.introduce());

this

: 함수를 어떻게 호출하느냐에 따라 this가 가리키는 대상이 달라짐.

profile
개발자국

0개의 댓글