객체와 객체가 메소드를 통해 상호작용하는 것
객체지향은 표현하고자 하는 사물을 추상적으로 표현
const Me = {
name : '김태희',
age : 26
studying : function(student){
student.levelUp;
}
}
const student = {
level = 1;
levelUp: function(){
this.level++;
}
}
Me.studying(student);
생성자 함수를 사용하는 이유: 같은 객체 안에 메소드와 프로퍼티를 동시에 생성할 수 있기 떄문
let snack = new Array('쿠키','초콜릿','커피');
💡 new의 역할
1. 새로운 함수를 생성해준다.
2. 생성자 함수 안의 this를 인스턴트로 바라보게 한다.
(코드 예시)
const snack = new Array('쿠키','초콜릿','커피');
function SnackList(menu){
this.menu = menu;
this.select = function(){
console.log(snack[0]);
}
}
const eat1 = new SnackList(snack);
const eat2 = new SnackList(snack);
eat1.select(); //쿠키
eat2.select(); //쿠키
SnackList.eat1 == SnackList.eat2 //false
생성자 함수의 issue 발생
💡 함수 내 this가 가르키는 영역
1. 일반 함수의 this는 소속된 함수를 가르킨다.
2. 생성자 함수 안의 this를 인스턴트로 가르킨다.
프로토타입은 DNA와 비슷하다. 부모 함수를 공유하지만 존재는 다르기 때문이다.
(프로토타입 코드 예시)
const snack = new Array('쿠키','초콜릿','커피');
function SnackList(menu){
this.menu = menu;
}
SnackList.prototype.select = function(){
console.log(snack[0]);
}
const eat1 = new SnackList(snack);
const eat2 = new SnackList(snack);
eat1.select(); //쿠키
eat2.select(); //쿠키
SnackList.prototype.eat1 == SnackList.prototype.eat2
//true
생성자 함수 issue 해결
function Boss(){
this.name = '보스태희';
}
Boss.prototype.rename = function(name){
this.name = name;
}
Boss.prototype.sayName = function(){
console.log(this.name);
}
const boss = new Boss();
// boss.name
// '보스태희'
// boss.rename('킹보스태희')
// undefined
// boss.name
// '킹보스태희'
// boss.sayName()
// 038.html:74 킹보스태희