13. 객체(method, this)

조뮁·2022년 7월 5일
0

JS기초

목록 보기
13/14
post-thumbnail

method

  • 객체 프로퍼티로 할당된 함수
// fly함수 = superman 객체의 method임
const superman = {
	name : 'clark',
    age : 33,
    fly : function(){ // method
    	console.log('날아갑니다 슈웅')
    }
}

superman.fly();
// "날아갑니다 슈웅" 
  • 단축구문
const superman = {
	name : 'clark',
    age : 33,
    fly(){  // function 키워드 생략가능
    	console.log('날아갑니다 슈웅')
    }
}

객체와 메소드의 관계

const user = {
  name : 'dal-bong',
  sayHello : function(){
    console.log(`Hello, -----`);
    console.log(`Hello, I'm ${this.name}`);
  },
}

user.sayHello();

다음과 같은 객체가 있을 때, sayHello라는 메소드에 객체의 name 프로퍼티를 넣고싶다!

  • 메소드에 ${this.property}와 같이 ${this} 키워드 사용
  • 객체의 메소드 호출 시, user.sayHello();에서 user는 sayHello 메소드 안의 ${this}

일반 함수에서의 this / 화살표 함수의 this

let boy = {
  name : 'Jakob',
  sayHello : function() {
    console.log(`Hello, My name is ${this.name}`);
  },
}

let girl = {
  name : 'Lisa',
  sayHello : function() {
    console.log(`Hello, My name is ${this.name}`);
  },
}
// this는 아직 결정되지 않음. 어떻게 호출하느냐에 따라 달라짐
// sayHello 함수를 각 객체의 메소드로 넣은 후 호출

let man = {
  name : 'Tom',
  sayHello : () => {
    console.log(this)
    console.log(`Hello, My name is ${this.name}`);
  },
}

boy.sayHello();
girl.sayHello();
man.sayHello();
  • 화살표함수는 일반함수와 달리 자신만의 this를 가지지 않음
  • 화살표 함수 내부에서 this를 사용하면, 그 this는 외부에서 값을 가져옴
  • 외부에서 가져오는 this = 전역객체 = window(브라우저환경) , global(Node js 환경)


  • 같은 객체를 바라보는 두 변수의 값 변경
// (1) boy 변수에 객체 할당
let boy = {
  name : 'bbbboy',
  showNm : function(){
    console.log(boy.name);
  }
}
boy.showNm();  // "bbbboy"

// (2) man에 boy를 할당
// boy객체에 man으로도 접근할 수 있음
let man = boy;
man.showNm();  // "bbbboy"

// (3) man.name 을 변경 -> man과 boy는 같은 객체를 바라보고 있기 때문에, man.showNm과 boy.showNm 모두 결과값이 바뀜
man.name = 'mmmmman';
man.showNm();  // "mmmmman"
boy.showNm();  // "mmmmman"

boy.name = 'bbboy2';
man.showNm();  // "bbboy2"
boy.showNm();  // "bbboy2"

// (4) boy는 사라졌기 때문에 boy.name과 boy.showNm 모두 동작하지 않는다.
boy = null;
man.showNm();  // Uncaught TypeError: Cannot read properties of null (reading 'name') 
boy.showNm();  // 
  • console.log('boy.name')(this.name)으로 변경
let boy = {
  name : 'bbbboy',
  showNm : function(){
    console.log(this.name);
  }
}
boy.showNm();  // "bbbboy"
let man = boy;
man.showNm();  // "bbbboy"

boy = null;
man.showNm();  // bbboy2
boy.showNm();  // Uncaught TypeError: Cannot read properties of null (reading 'name') 

결론 : 메소드에서는 객체명을 직접 써주기보다는, this를 활용하는 것이 좋음


  • 메소드에서 화살표함수 사용
let boy = {
  name : 'bbbboy',
  sayHello : () => {
    console.log(this);
  }
}

boy.sayHello();
>> /* Log Skipped: Sorry, this log cannot be shown. You might need to use the browser console instead. */
  • 메소드 내 화살표함수에서 this를 사용하면 this는 객체(boy)를 가르키는게 아니라, 전역객체를 가르킨다.

객체의 메소드를 작성할때는 화살표함수로 작성하면 안됨




0개의 댓글