240721 메소드 (Method)

신한별·2024년 7월 20일

💪 매일 기록

목록 보기
18/97
let greetings = { // 프로퍼티 값으로 함수를 정의
  sayHello : function () {
  	console.log('Hello!');
  },
  sayHi : function(name) {
  	console.log(`Hi! ${name}!`);
  },
  sayBye : function() {
    console.log('Bye!');
  }
}; 	

greetings.sayHello(); // Hello! 출력
greetings.sayHi('소희'); // Hi! 소희! 출력
greetings['sayHi']('소희'); // Hi! 소희! 출력

/////////////////////////////////////////////////////

let rectAngle = {
	width : 30,
  	height : 50,
  	getArea : function() {
    	return rectAngle.width * rectAngle.height;
    }
}

let triAngle = {
  	width : 15,
  	height : 40,
  	getArea : function() {
    	return triAngle.width * triAngle.height / 2;
    }  
}

메소드 활용의 장점 🤗

  1. 다른 함수의 이름 중복을 피할 수 있다.
  2. 객체에 집중해서 함수의 동작을 작성할 수 있다.
  3. 사용 시 객체의 고유한 동작으로 구분할 수 있다.

0개의 댓글