IT Log

JavaScript (6) 본문

JavaScript

JavaScript (6)

newly0513 2020. 6. 14. 13:09
728x90
반응형

Error

  • try : 코드 블록에서 오류가 있는지 테스트
  • catch : 오류를 처리
  • throw : 사용자 지정 오류 생성
  • finally : 결과와 상관없이 시도 후 catch후에 코드를 실행
try {
  Block of code to try
}
catch(err) {
  Block of code to handle errors
}
[ finally {
   Code that is always executed regardless of 
   an exception occurring
}]



function myFunction() {
  var message, x;
  message = document.getElementById("p01");
  message.innerHTML = "";
  x = document.getElementById("demo").value;
  try { 
    if(x == "")  throw "is empty";
    if(isNaN(x)) throw "is not a number";
    x = Number(x);
    if(x > 10)   throw "is too high";
    if(x < 5)  throw "is too low";
  }
  catch(err) {
    message.innerHTML = "Input " + err;
  }
  finally {
    document.getElementById("demo").value = "";
  }
}

Error 속성

  • name : 오류 이름을 설정하거나 반환
  • message : 오류메시지를 설정하거나 반환

Error name 값

  • EvalError : eval(). 함수에서 오류 발생 (최신 JavaScript에서는 발생하지 않음) 
  • RangeError : 범위를 벗어난 숫자가 발생
  • ReferenceError : 잘못된 참조가 발생
  • SyntaxError : 구문 오류가 발생
  • TypeError : 유형 오류가 발생
  • URIError :  encodeURI() 오류가 발생

Validation

  • 기본 : 모든 필수 필드가 채워져 있는지 확인
  • 데이터 형식 검증 : 입력된 데이터가 올바른 형식과 값인지 확인
# 기본 형식
function validate() {
      
         if( document.myForm.Name.value == "" ) {
            alert( "Please provide your name!" );
            document.myForm.Name.focus() ;
            return false;
         }
         if( document.myForm.EMail.value == "" ) {
            alert( "Please provide your Email!" );
            document.myForm.EMail.focus() ;
            return false;
         }   
         return( true );
}


# 데이터 형식
function validateEmail() {
         var emailID = document.myForm.EMail.value;
         atpos = emailID.indexOf("@");
         dotpos = emailID.lastIndexOf(".");
         
         if (atpos < 1 || ( dotpos - atpos < 2 )) {
            alert("Please enter correct email ID")
            document.myForm.EMail.focus() ;
            return false;
         }
         return( true );
}

this

자신이 속한 객체를 나타냄

  • Method : 소유자 객체를 나타냄
  • Alone : 전역 객체를 나타냄
  • function : 전역 객체를 나타냄
  • strict mode에서 function : undefined를 나타냄
  • event : 이벤트를 받은 요소를 나타냄
  • call(), apply() : 모든 객체에 this를 참조할 수 있음
# 함수
function window() {
  return this;
}
// this의 값은 [object Window]

# Object안의 함수
var order = {
  first  : "첫번째",
  second : "두번째",
  no  : 13,
  orderList : function() {
    return this;
  }
};
// 여기에서 this는 order (this.first는 order.first와 같다)

# call()
var order1 = {
  orderList: function() {
    return this.first + " " + this.second;
  }
}
var order2 = {
  first: "첫번째",
  second: "두번째",
}
order1.orderList.call(order2); 
// 첫번째 두번째

그 외 기타 등등

연산

  • JavaScript 숫자는 64비트 Float으로 저장됨
# 나올 수 있는 상황
0.1+0.2=0.30000000000000004

# 해결방법
(0.1 * 10 + 0.2 * 10) / 10 = 0.3

세미콜론

  • JavaScript는 줄 끝에서 명령문을 자동으로 닫음
# 동일한 결과
function 함수(){
	var x = 10
    return 10*x
}

function 함수(){
	var x = 10;
    return 10*x;
}

undefined

  • 객체 존재여부를 테스트 할 수 있음
  • null로는 테스트 할 수 없음
  • undefined와 null같이 테스트하는 경우 null이 먼저 나오면 안됨
# undefined로 테스트하는 경우
if (typeof test === "undefined") 

# null로 테스트하는 경우 값은 항상 false라 비교할 수 없음
if (test === null) 

# undefine과 null을 같이 쓰는 경우 아래와 같이 작성
if (test === undefined && test === null) 
typeof null (===) undefined (===) undefined && null (===)
선언하지않음 false true  
선언만 false false false
값과 선언 false false false

 

728x90
반응형

'JavaScript' 카테고리의 다른 글

JavaScript (5)  (0) 2020.06.13
JavaScript (4)  (0) 2020.06.13
jQuery Tutorial (3)  (0) 2020.06.09
jQuery Tutorial (2)  (0) 2020.06.09
jQuery Tutorial (1)  (0) 2020.06.08
Comments