JavaScript에서는 객체를 생성한 후에도 언제든지 새로운 속성(property)과 메서드(method)를 동적으로 추가할 수 있습니다. 가장 간단하고 널리 사용되는 방법은 점 표기법(dot notation)으로, 객체명.속성명 = 값 형태로 작성하면 됩니다.
객체에 속성·메서드를 추가하는 주요 방법
- 점 표기법(Dot Notation):
object.property = value - 대괄호 표기법(Bracket Notation):
object['property'] = value— 속성 이름에 공백이나 특수문자가 있을 때 유용합니다. - Object.defineProperty(): enumerable, writable 등 세부 옵션까지 지정해야 할 때 사용합니다.
예제
다음은 빈 객체에 버튼 클릭 시점에 속성과 메서드를 추가하고, 그 결과를 화면에 출력하는 전체 코드입니다.
<!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;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Add properties and methods to an existing object in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add property and methods to student object and display
them</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let student = {
};
BtnEle.addEventListener("click", () => {
student.name = 'Rohan Sharma';
student.age = 16;
student.place = 'Delhi';
student.displayInfo = function(){
return 'Name = '+this.name+' : Age = '+this.age+' : Place = '+this.place;
}
resEle.innerHTML += student.displayInfo();
});
</script>
</body>
</html>출력 결과
페이지가 처음 로드된 상태입니다.

'CLICK HERE' 버튼을 클릭하면 — student 객체에 추가된 displayInfo() 메서드가 실행되어 이름, 나이, 지역 정보가 화면에 표시됩니다.

코드 설명
위 예제의 동작 흐름은 다음과 같습니다.
- 비어 있는
student객체를 생성합니다. - 버튼 클릭 이벤트가 발생하면 점 표기법을 사용해
name,age,place세 개의 속성을 동적으로 추가합니다. displayInfo라는 메서드를 함수로 할당합니다. 메서드 내부에서는this키워드를 통해 객체 자신의 속성 값에 접근하여 하나의 문자열로 조합해 반환합니다.- 반환된 문자열을
.result영역의 innerHTML에 추가하여 화면에 출력합니다.
이처럼 JavaScript의 객체는 유연하게 확장할 수 있어, 실행 중인 상황에 따라 필요한 데이터와 동작을 자유롭게 덧붙일 수 있습니다.