본문 바로가기
💻CODING/javascript

[js] 생성자 패턴/인스턴스(ft. this, 팩토리 패턴과의 비교)

by 코딩하는 갓디노 2021. 2. 26.

[js] 생성자 패턴/인스턴스(ft. this, 팩토리 패턴과의 비교)

 

생성자 패턴을 팩토리 패턴과
비교하여 알아보겠습니다.

 

생성자/인스턴스

  • 객체지향 프로그래밍입니다.
  • 객체를 생성하는 함수를 생성자(constructor) 함수라고 부릅니다. 
  • 함수 이름 첫 글자를 대문자로 표기하는 것이 규칙입니다.
  • this, new를 사용합니다.
  • new를 이용하여 함수처럼 호출합니다.
  • 생성자 함수가 다른 언어의 class의 역할을 대신합니다. 

 

팩토리 패턴

팩토리 패턴과 Object.create()를 이용하여 프로토 타입을 적용한 패턴 예제

let prototype = {
  type: 'friend',
  personality: function() {
    console.log('nice');
  }
}

function friendMaker(name, age, job, sex) {
  let friend = Object.create(prototype);
  friend.name = name;
  friend.age = age;
  friend.job = job;
  friend.sex = sex;
  return friend;
}
friendMaker('박지수', 30, 'nurse', 'female');

 

결과

{name: "박지수", age: 30, job: "nurse", sex: "female"}
age: 30
job: "nurse"
name: "박지수"
sex: "female"
__proto__:
personality: ƒ ()
type: "friend"
__proto__: Object

 

생성자 패턴

예제

 let prototype = {
   type: 'friend'
 }

 function FriendMaker(name, age, job, sex) {
   this.name = name; //this
   this.age = age;
   this.job = job;
   this.sex = sex;
 }
 FriendMaker.prototype = prototype; 

 new FriendMaker('박지수', 30, 'nurse', 'female'); //new
 //new를 붙이는 순간 FriendMaker 객체가 생성 된다.

 

결과

FriendMaker {name: "박지수", age: 30, job: "nurse", sex: "female"}
age: 30
job: "nurse"
name: "박지수"
sex: "female"
__proto__:
type: "friend"
__proto__: Object

 

proto 타입 적용 형식

팩토리 패턴

변수.__proto__ =  프로토타입 변수

 

생성자 패턴

함수이름.prototype = prototype;

 

this

  • this는 기본적으로 window입니다.  
  • this는 함수를 호출할때 결정이 됩니다. (이전에는 모름)

 

this가 window에서 바뀌는 경우

  • 객체가 메서드처럼 사용될 때 this가 window에서 객체 자신으로 바뀝니다.(this 예제1)
  • 화살표 함수에서는 this가 바뀌지 않고 무조건 부모의 this를 받아옵니다. (객체가 메서드처럼 사용되더라도, this 예제2)
  • new(생성자)가 적용될때 this가 window에서 생성자 함수 자신을 가리킵니다. (this가 window -> 함수 자신으로 바뀌게 됨)
  • this에 저장된 것들은 new를 통해 객체를 생성할 때 그 객체에 적용됩니다.

 

this 예제1 - 객체가 메서드처럼 사용될때 - 함수 앞에 객체가 붙을때

const obj = {
	name: 'goddino',
	sayName() {
	console.log(this.name);
	}
};

obj.sayName(); //sayName 함수 앞에 obj이라는 객체가 붙을 때 this는 obj 객체가 됨
//goddino

 

this 예제2 - 화살표 함수

const obj = {
	name: 'goddino',
	sayName : () => { //화살표 함수
	console.log(this.name);
	}
};

obj.sayName() //객체가 함수 앞에 있더라구도 함수가 화살표 함수면 this는 windwo
//결과 값이 window.name 이므로 아무것도 나오지 않음

 

this 예제3

const obj = {
  name: 'goddino',
  sayName() {
    console.log(this.name); //결과 goddino - obj.sayName() 이므로 this가 obj로 바뀜

    function inner() {
      console.log(this.name); //결과 window.name 이므로 없음 inner()가 this가 window에서 안바뀜
    }
    inner(); //this가 안바뀜
  }
};

obj.sayName() //this가 바뀜

 

this 예제4

  • 항상 함수를 호출할때 this를 봄
  • inner() 에서는 this를 바꾸지 않음
  • () => {} 화살표 함수에서 부모 함수의 this를 가져옴
  • 부모 함수는 sayName, sayName의 this는 sayName() 으로 호출하였기 때문에 goddino
  • goddino를 그대로 따름
const obj = {
	name: 'goddino',
	sayName () {
	console.log(this.name); //goddino
	const inner = () => {
		console.log(this.name); //goddino
		}
	inner();
	}
};

obj.sayName()

 

함수 종류별 this

  • this는 함수 호출할 때 정해집니다.
  • 일반 함수(function () { })는 호출 위치에 따라 this 정의
  • 화살표 함수(() => { })는 자신이 선언된 함수 범위에서 this 정의

 

this 예제

  • new라는 키워드 User라는 생성자 함수를 Goddino라는 인수를 넣어 생성하여
    goddino라는 인스턴스를 만들어 줍니다. 
  • normal 메소드가 실행되는 호출되는 위치에 연결되어있는 객체, Goddino가 this 키워드가 됩니다. 
  • arrow 메소드는 자신이 선언된 함수 범위가 없기 때문에 undefined가 됩니다.  
function User(name) { //User라는 생성자 함수
  this.name = name;
}
User.prototype.normal = function() { //normal 메소드(일반 함수)
  console.log('normal', this.name);
}

User.prototype.arrow = () => { //arrow 메소드(화살표 함수)
  console.log('arrow', this.name);
}

const goddino = new User('Goddino'); //goddino 인스턴스 = new User('Goddino'); Goddino 인수

goddino.normal(); //결과: normal Goddino 
goddino.arrow(); //결과: arrow undefined

 

 

 

반응형

댓글