사용자 정의 객체  -- 클래스를 작성

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">

//    자바 스크립트의 사용저 정의 객체
   
// -- 클래스를 작성
//    function 클래스명(파라미터변수들...){
//        this.속성명;// 속성 선언만
//        ..
//        this.속성명2 = 값 ;// 속성 선언및 초기화
//        ..
//        this.메서드명 = 실제함수명;
//    }
//   
//    function 실제함수명(파라미터 변수들){
//    처리내용;;
//    ..
//    ..
   
// -- 2. 객체를 만들고 , 사용하기
//var 객체변수1 = new 클래스명(값들...);
//var 객체변수2 = new 클래스명(값들...);

//객체변수1.속성명 = 값;
//객체변수1["속성명"]=값;
//
//객체변수1.메소드명(값들...)
 var Member = function(id, name, juminNo){
  this,id = id;
  this.name = name;
  this.juminNo = juminNo;
 }

 //

 // 클래스에 메소드 추가 (prototype명령을 이용한다.)

 // 속성값을 다른 값으로 변경하는 메소드
 Member.prototype.setValue = function(newId, newName, newJuminNo){
  this,id = newId;
  this.name = newName;
  this.juminNo = newJuminNo;
 }
 
 // 주민번호를 이용 나이를 계산하는 메소드
 Member.prototype.getAge = function(){
  var today = new Date();
  var currYear = today.getFullYear();

  var juminYear = Number( this.juminNo.substring(0,2) );
  var flag = this.juminNo.charAt(7); // 성별자리값 읽기

  if(flag=="1" || flag=="2") { // 1900년대 사람
   juminYear += 1900;
  }else{ // 2000년대 사람
   juminYear += 2000;
  }
 
  return (currYear - juminYear);
 }

 // 속성값을 문자열로 구성하여 반환하는 메소드
 Member.prototype.toString = function(){
  return this.id + "[" + this.name + "]" + this.getAge() + "세";
 }

 //------------------------------------------------------------------------

 // 객체생성 및 사용하기 -------

 var mem = new Member("gildong", "홍길동", "800101-1234567");

 var result = mem.toString();

 alert("변경전 : " + result);

 mem.setValue("jimae", "일지매", "000808-3456789");
 result = mem.toString();
 alert("변경후 : " + result);
 
 // 생성된 객체에 새로운 속성과 메소드 추가 하기
 mem.tel  = "042-3222-5453";
 mem.addr = "대전시 중구 대흥동 500번지 " ;
 mem.display= function(){
     var str = "";
     str +="ID : " +this.id +"\n";
     str +="이름 : " +this.name +"\n";
     str +="주민번호 : " +this.juminNo +"\n";
     str +="전화번호 : " +this.tel +"\n";
     str +="주소 : " +this.addr +"\n";
    alert(str);
 }
 
 mem.display();
 
 var mem2 = new Member("ddit","대덕","770707-121212");
alert(mem2.addr);

 
 
   </script>
</head>
<body>

</body>
</html>

 

오브젝트의 속성 추가

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
    // 객체를 생서한 후 생성도니 객체에 속성과 메소드를 추가 할수 있다.
   
    // Object() => 빈 객체를 만들어 준다.
   
    var mem = new Obect();
   
    // 생성된 객체에 속성 추가
    mem.id = "gildone";
    mem.name = "홍길동";
    mem_addr = "대전" ;
   
    mem.toString = function(){
        var str = "이름 : "+this.name + "\n";;
        str += "ID : "+this.id + "\n";
        str +="주소 : "+ this.addr;
       
        alert(str);
    }
   
    //alert(mem.id);
    mem.toString();
   
//---------------------
  </script>
</head>
<body>

</body>
</html>

JSON 표기법-- 자바스크립트 오브젝트 심플 표기법

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>img 커텐 효과 </title>
  <script type="text/javascript" src="./js/jquery-1.7.2.js"></script>
  <script type="text/javascript">
     //JOSN 표기법
   
    // 1. 이름:값 형식
   
    var mem= {id : "power2c","name" : "일지매",addr: "대전"};
   
    document.write(mem.name+ "씨!!<br>당신은 ID가 "+mem.id+"이고, " +mem.addr+"에 사시는군요 !! <br><br>");

    // 2. 배열 형식
    var names = ["홍길동","일지매","변학도","성춘향","이몽룡"];
   
    for(var i=0;i<names.length;i++){
        document.write("names["+i+"] j = "+ names[i]+"<br>");
       
       
    }
    document.write("<br><hr color='red'><br> ")
 
  </script>
</head>
<body>

</body>
</html>

 

사용자 객체 생성및 사용

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript" src="./js/jquery-1.7.2.js">
        </script>
        <script type="text/javascript">
/*
    학번, 이름, 국어점수 , 수학점수, 컴퓨터 점수, 총점, 평균을 기억할 속성을 갖고
    총점과 평균은 메소드를 이용하여 구하는 클래스를 작성 하시오. 

    속성
        학번,이름,국어,수학,컴퓨터,총점,평균
    메소드
        총점구하기
        평균구하기
        결과출력하기
 */
    var Student= function(myNo,myName,myKor,myMat,myCom) {
        this.no =myNo;
        this.name=myName;
        this.kor=myKor;
        this.mat=myMat;
        this.com=myCom;
        this.tot=this.getTot();
        this.avg=this.getAvg();
       
    };
    Student.prototype = {
        getTot : function(){
                var tot = this.kor+this.mat+this.com;
                 return tot;
                 },
        getAvg : function(){
            if(typeof(this.tot)=="undefined"){
                //값이 없는경우 typeof 처리 시에 undefined 라는 문자열이 반환
            }
           
            var avg = this.tot/3;
                return parseInt(avg);
        },
        getDisplay : function(){
            document.write("No : "+this.no+"<br>");
            document.write("name : "+this.name+"<br>");
            document.write("kor : "+this.kor+"<br>");
            document.write("mat : "+this.mat+"<br>");
            document.write("com : "+this.com+"<br>");
            document.write("tot : "+this.tot+"<br>");
            document.write("avg : "+this.avg+"<br>");
        }

    };
   
    var sut = new Student(15,"김훈",82,90,100);
    sut.getDisplay();
            
              
        </script>
    </head>
    <body>
    </body>
</html>

 

추가 JSON 설명

 

 

Introducing JSON - 원문보기

 

참고사항 : 한국어로 번역했을 때 개발자로서 접근하기 불편한 것들은 그냥 한글 발음으로 표기했음.

ex> object -> 오브젝트, format -> 포맷 등

 

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

JSON(자바스크립트 오브젝트 표기법) 은 가벼운 데이터 변환 포맷이다. (즉, 여러가지 언어에서 사용하는 데이터 표현방식을 한가지로 표준화 해서 사용하겠다 라는 말이다. 그런데 발음이... 제이슨? 제이손?제이썬? 뭐가 맞는것인지... 당췌! 자신있는 분 답글 부탁합니다 ㅋㅋ)

 

It is easy for humans to read and write. It is easy for machines to parse and generate.

사람이 읽고 쓰기 편하다. 기계가 분석하고 생성하기가 편하다. (사람도 편하고 기계도 편하다. 꿩먹고 알먹기? 그럼 꿩은 멸종되는 것인가.. ㅡ.ㅡ; )

 

It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.

JSON 은 1999년 12월에 발표된 ECMA-262(에크마-262) 표준 3번째 에디션의 자바스크립트 프로그래밍 언어의 일부를 기반으로 한다.

 

JSON is a text format that is completely language independent

JOSN 은 완전히 프로그램언어와 상관없는 문자 포맷이다.

 

but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

버뜨! 그러나 C, C++, C#, Java, JavaScript, Perl, Python, 기타등등의 C 언어 패밀리 ( C 문법과 유사한 언어들을 의미하는거 같음. 아님말고 ㅡㅡ+) 프로그래머들이 사용하는 형태와 비스무리하다. (번역이 좀 이상하다 - 그냥 의미만 이해하다.)

 

These properties make JSON an ideal data-interchange language.

이런 특징이 JOSN 을 데이타 변환 언어로 사용하게끔 만든다. (왜냐! 거의 모든언어를 사용할 수 있으니까!!)

 

 

JSON is built on two structures:

JSON 은 2가지 구조다.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • 이름/값  이런형식의 집합 : 많은 언어들이 이놈들을 오브젝드, 레코드, 구조체, 딕셔너리, 해쉬테이블, 키값을 가진 리스트, 연상배열(인덱스가 아닌 키값으로 접근 가능한 배열) 로 인식된다.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
  • 값들이 순서대로 나열된 것들 : 대부분 배열, 벡터, 리스트, 시퀀스로 인식한다.

These are universal data structures.

이놈들은 통합된 데이터 구조이다.

 

Virtually all modern programming languages support them in one form or another.

왠만한 언어들이 위에 나열된 데이터형식들을 사용한다는 말이다.

 

It makes sense that a data format that is interchangable with programming languages also be based on these structures.

즉, 이러한 구조를 기반으로 하는 프로그램 언어들은 서로 데이터를 주고 받을 수 있다~~ 라는 말.

 

In JSON, they take on these forms:

JOSN 은 3가지 형식으로 사용되는데....

 

An object is an unordered set of name/value pairs.

오브젝트는 순서 상관없이 이름/값으로 이루어진이다.

 

An object begins with { (left brace) and ends with } (right brace).

{ 로 시작해서 } 로 끝난다. { ~~~ }

 

Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

'이름' 하고 '값' 은 : (콜론) 으로 구분하고 여러개 구분할때는 , (콤마)로 한다.

요롷게,  { 이름1:값1 , 이름2:값2, ... }

 

 

 

An array is an ordered collection of values.

배열은 순서가 있는 값들의 집합이다.

 

An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

[ 로 시작해서 ] 로 끝나고 마찬가지로 , 로 여러개 구분한다.

요롷게, [ 배열1, 배열2, 배열3, ... ]

 

 

 

 

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.

'값'은 " (썅따옴표) 로 싸고있는 문자열, 숫자, 참/거짓, NULL, 오브젝트, 배열을 쓸 수 있다.

 

These structures can be nested.

당근 중첩될 수 있다.

 

 

 

A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.

문자열은 \ (역슬래쉬) 를 이용해서 특수 문자를 넣을 수도 있고, 아예 빈값도 되고, 유니코드도 된다. 단, " 로 감싸줘야 된다.

 

A character is represented as a single character string. A string is very much like a C or Java string.

한글자도 문자열로 취급한다. (char 가 아닌 string... 이해 안되면 자바기초 공부하세요)

 

 

 

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

숫자는 C 랑 Java 하고 비스무리 한데, 8진수, 16진수는 안된다.

 

Whitespace can be inserted between any pair of tokens.

공백은 " 로 감싼 문자열 빼고 어디들 올 수 있다.( 문자열안에 있는 공백 빼고 나머지는 무시한다는 얘기)

 

Excepting a few encoding details, that completely describes the language.

몇가지 규칙빼고 전부 설명했다.

 

-- 원문보기 가보시면 왠만한 언어들은 다 지원된다는 것을 알 수 있습니다.

-- 예제는 안 적었습니다. 구굴링 해보면 나오니까요 ㅋㅋ

-- 나름대로 이해하기 쉽게 설명한다고 했는데... 쉬운지 모르겠네요 ^^;

    조금이라고 도움이 되셨기를...

 

이 글은 스프링노트에서 작성되었습니다.

'J-Query' 카테고리의 다른 글

list 추출및 select 구현  (0) 2012.05.08
9일차 XML문서  (0) 2012.05.08
7일차 Effects  (0) 2012.05.08
6일차 Utilities  (0) 2012.05.08
5일차 찾기관련()eq()..  (0) 2012.05.08
Posted by 사라링
BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
VM-WARE (0)
디자인패턴 (1)
스크랩 (0)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
Total :
Today : Yesterday :