JavaScript에서 'new' 연산자를 사용하면 생성자(constructor) 함수를 기반으로 새로운 객체 인스턴스를 간편하게 만들 수 있습니다. 'new' 연산자가 실행되면 빈 객체가 먼저 생성되고, 생성자 함수 내부의 this 키워드가 해당 객체를 가리켜 속성이 할당된 뒤, 완성된 객체가 반환됩니다.
예제
<!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>JavaScript constructor using new</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to create JavaScript constructor using new operator</h3>
<script>
let resEle = document.querySelector(".result");
function Human(firstName,lastName,age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
let obj = new Human('Rohan','Sharma',22);
document.querySelector(".Btn").addEventListener("click", () => {
for(i in obj){
resEle.innerHTML += 'Key = ' + i + ' : Value = ' + obj[i] + '<br>'
}
});
</script>
</body>
</html>
코드 설명
Human생성자 함수는 이름(firstName), 성(lastName), 나이(age)를 매개변수로 받아this키워드를 통해 객체 속성에 할당합니다.new Human('Rohan', 'Sharma', 22)를 호출하면 새로운 객체가 생성되어 변수obj에 저장됩니다.- 버튼을 클릭하면
for...in루프를 통해 객체의 모든 키(key)와 값(value)이 화면에 순서대로 출력됩니다.
출력
위 코드를 실행하면 다음과 같은 결과가 표시됩니다.

'CLICK HERE' 버튼을 클릭한 후의 결과입니다.
