아래와 같이, 객체안에 함수를 선언함으로써 중복코드를 없애고 간결하게 나타낼 수 있다.
<script>
window.onload = function(){
var btnPrint = document.getElementById("btn-print");
btnPrint.onclick = function(){
var x = prompt("x값을 입력하세요.",0);
var y = prompt("y값을 입력하세요.",0);
x = parseInt(x);
y = parseInt(y);
btnPrint.value = x+y;
};
}
</script>
<input type="button" value="클릭" id="btn-print"/> <br/>
<span id = "span1">스팬입니다.</span>