JavaScript 객체를 이용한 JS파일 생성
JavaScript
문제점 😅
JSP를 수정하다 보면 용도에 따른 JS 파일이 import 되어있는 경우를 많이 접한다. 특정 업무에 필요한 함수나 변수를 따로 JS 파일로 관리하면 유지보수가 용이해진다. 그럼 이런 JS 파일은 어떻게 만들면 될까?
해결책 😏
공용 함수 및 변수 등을 가지는 commonUtil.js를 만들고 index.html에서 사용해보자. 두 파일은 같은 경로에 위치해 있다.
commonUtil.js
/*객체를 이용하여 변수 및 함수 프로퍼티 작성*/
let MyUtil = {
summary: "calculation !!",
add: (n1, n2) => {
if(checkParam(n1, n2)){
let result = n1 + n2;
alert(`${n1} + ${n2} = ${result}`)
}
},
minus: (n1, n2) => {
if(checkParam(n1, n2)){
let result = n1 - n2;
alert(`${n1} - ${n2} = ${result}`)
}
},
multiply: (n1, n2) => {
if(checkParam(n1, n2)){
let result = n1 * n2;
alert(`${n1} * ${n2} = ${result}`)
}
},
divide: (n1, n2) => {
if(checkParam(n1, n2)){
let result = n1 / n2;
alert(`${n1} / ${n2} = ${result}`)
}
}
};
/*파라미터 함수 체크 선언*/
function checkParam(n1, n2){
console.log('n1 Type: '+typeof n1+' / n2 Type: '+typeof n2);
if(typeof n1 !== 'number'){
alert('n1 is NOT number.');
return false;
}
if(typeof n2 !== 'number'){
alert('n2 is NOT number.');
return false;
}
return true;
}
commonUtil.js에는 <script>
태그 안에 들어갈 내용만 기술하면 된다. 자바스크립트 객체의 장점 중 하나는 함수를 프로퍼티로 저장할 수 있다는 것이다.
index.html
<html>
<head>
<title>TEST</title>
</head>
<body>
<script src="commonUtil.js"></script>
<script>
console.log(MyUtil.summary); // calculation !!
MyUtil.add(100,5); // 100 + 5 = 105
</script>
</body>
</html>
이제 HTML, JSP 등에서 객체 MyUtil에 점(.)으로 객체 내의 변수 및 함수를 접근할 수 있다. 브라우저 개발자 도구 콘솔창에서도 객체로 접근하여 값을 확인할 수 있다.
마무리 😎
이런 형식으로 필요한 유틸 스크립트 파일을 따로 관리하거나 생성하는 경우가 있다. 자바스크립트 객체에 대해서 알아둬야한다.
참고문헌 📝
https://ko.javascript.info/object
https://ko.javascript.info/primitives-methods