JavaScript에서 객체(Object)는 단순히 데이터를 담는 컨테이너가 아니라, 함수 형태의 메서드(method)도 함께 포함할 수 있습니다. 객체 메서드를 활용하면 객체 내부의 속성값을 기반으로 다양한 동작을 수행할 수 있어 코드의 재사용성과 가독성이 크게 향상됩니다.
객체 메서드 추가 및 접근 예제
다음은 JavaScript 객체에 메서드를 추가하고 이를 접근하는 전체 코드입니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Add, Access JavaScript object methods</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CHECK</button>
<h3>Click on the above button to add and access object methods.</h3>
<script>
let resEle = document.querySelector(".result");
let obj = {
firstName:'Rohan',
lastName: 'Sharma',
Age:'22',
}
document.querySelector(".Btn").addEventListener("click", () => {
obj.welcome = function(){return 'Welcome '+this.firstName+' '+this.lastName};
resEle.innerHTML = 'Adding function welcome : ' + obj.welcome + '';
resEle.innerHTML += 'Accessing function welcome : ' + obj.welcome() + '';
});
</script>
</body>
</html>
출력 결과
위 코드를 실행하면 다음과 같은 초기 화면이 표시됩니다.

'CHECK' 버튼을 클릭하면 아래와 같이 객체에 새로 추가된 welcome 메서드의 정의와 호출 결과가 함께 출력됩니다.

코드 상세 설명
1. 객체 정의
먼저 firstName, lastName, Age라는 세 개의 속성을 가진 obj 객체를 생성합니다. 이 객체에는 아직 메서드가 없으며, 사용자가 버튼을 클릭했을 때 동적으로 추가됩니다.
2. 메서드 동적 추가
버튼 클릭 이벤트가 발생하면 점 표기법(dot notation)을 사용하여 obj.welcome이라는 새로운 메서드를 객체에 추가합니다. 이때 this 키워드는 해당 메서드가 속한 객체 자신을 가리키므로, this.firstName과 this.lastName을 통해 객체의 속성값에 안전하게 접근할 수 있습니다.
3. 메서드 접근과 호출의 차이
obj.welcome처럼 소괄호 없이 접근하면 함수의 정의 자체가 문자열로 반환되어 화면에 그대로 표시됩니다. 반면 obj.welcome()처럼 소괄호를 붙여 호출하면 함수가 실제로 실행되어 'Welcome Rohan Sharma'라는 반환값이 출력됩니다. 이 두 가지 접근 방식의 차이를 이해하는 것이 객체 메서드를 올바르게 활용하는 핵심입니다.