웹_프론트_백엔드/프론트엔드

2020.09.19

shine94 2020. 9. 22. 00:22

1. 자바스크립트는 오해할 수 있으나 완벽한 객체지향 언어가 아닌 객체 기반의 스크립트 프로그래밍 언어이다.

   원래는 프로토타입 언어였고 추후 객체 필요성으로 인해 객체 기능이 들어간 것이다.

 

 

2. 객체(Object)
 : 키(key)와 값(value)으로 구성된 프러퍼티(property)들의 집합.

   프로퍼티의 값은 자바스크립트에서 사용할 수 있는 모든 값을 담을 수 있다.

 

   // 배열
   const student = ['김사과', '반하나', '오렌지'];


   // 객체
   const student1 = { num:1, name:'김사과', kor:90, math:100, eng:60 };
   const student2 = { num:2, name:'반하나', kor:100, math:40, eng:60 };

 

   // 객체 배열
   const student = [
       { num:1, name:'김사과', kor:90, math:100, eng:60},
       { num:2, name:'반하나', kor:100, math:40, eng:60}
   ];

 

** 1_객체.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>객체</title>
</head>
<body>
    <h2>객체</h2>
    <script>
        'use strict';
        const dog1 = "뽀미";
        const dog2 = {
            name: "루시",
            family: "포메리안",
            color: "white",
            age: 9,
            weight: 3.5,
            play: function(){
                console.log("뛰어놉니다.");
            }
        };

        console.log(`dog1 : ${dog1}`);
        console.log(`dog2 : ${dog2}`);

        // console.dir() : 객체의 모든 프러퍼티를 확인하는 함수
        //                 하위 개체의 내용을 볼 수 있는 펼침 삼각형이 있는 계층적 목록으로 표시
        console.dir(dog2); 

        // 프러퍼티의 값을 찍기 위해서는 어떻게 해야하는가?
        console.log(`dog2.name : ${dog2.name}`);
        console.log(`dog2.family : ${dog2.family}`);
        console.log(`dog2.color : ${dog2.color}`);
        console.log(`dog2.age : ${dog2.age}`);
        console.log(`dog2.weight : ${dog2.weight}`);
        console.log(`dog2.play : ${dog2.play}`);
        dog2.play();
    </script>
</body>
</html>

 

** 실행결과

 

 

3. 프러퍼티

 : 프러퍼티는 키(이름)와 프로퍼티 값으로 구성된다.

   키로 유일하게 값을 식별할 수 있다.

   프러퍼티 키는 프러퍼티를 식별하기 위한 식별자이며,

   프러퍼티 값으로 사용할 수 있는 값은 빈 문자열을 포함하는 모든 문자열 또는 symbol값이다.

   [예] dog                 // 필드 + 메소드 = 프러퍼티

         이름 : 루시        // 필드

         종 : 포메리안     // 필드

         색상 : 흰색        // 필드

         나이 : 9살         // 필드

         몸무게 : 3.5kg    // 필드

         행동 : 뛰어놀기  // 메소드

 

   [위의 예시를 소스로 표현하면?]

   const dog = {

       name: '루시',       // 필드

       family: '포메리안', // 필드

       color: 'white',       // 필드

       age: 9,               // 필드

       weight: 3.5,         // 필드

       play: function() {  // 메소드

           console.log('뛰어놀기');

       }

   }

 


4. 객체를 생성하는 방법
1) 리터럴 표기법을 이용한 객체의 생성
 : 자바스크립트에서 객체를 생성하는 가장 쉽고, 간단한 방법이다.

   const 객체이름 = {
       프러퍼티명1 : 값1,
       프러퍼티명2 : 값2,
       ...
       프러퍼티명n : function() {  }
       ...
   }

 

2) 생성자를 이용한 객체의 생성
 : new 연산자를 사용하여 객체를 생성하고 초기화 할 수 있다.

   이 때 사용되는 메소드를 생성자라고 하며, 이 메소드는 새롭게 생성되는 객체를 초기화하는 역할을 한다.

 

   function 생성자이름(매개변수1, 매개변수2, ... ) {
       프러퍼티이름1 = 값1;
       프러퍼티이름2 = 값2;
       ...
       프러퍼티이름n = function(){  }
       ...
   }

   const 객체이름1 = new 생성자이름(값1, 값2, ... );
   const 객체이름2 = new 생성자이름(값1, 값2, ... );
   ...
   const 객체이름n = new 생성자이름(값1, 값2, ... );

 

** 2_생성자.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>생성자</title>
</head>
<body>
    <h2>생성자</h2>
    <script>
        'use strict';
        function triangle(b, h) {
            this.base = b;
            this.height = h;
            this.area = function() {
                return this.base * this.height / 2;
            }
        }
        // 객체 생성
        const tg1 = new triangle(10, 10);
        const tg2 = new triangle(20, 5);

        // 객체 값 접근
        console.log(`tg1.base : ${tg1.base}`);
        console.log(`tg1.height : ${tg1.height}`);
        console.log(`tg1.area() : ${tg1.area()}`);
        console.dir(tg1);

        console.log(`tg2.base : ${tg2.base}`);
        console.log(`tg2.height : ${tg2.height}`);
        console.log(`tg2.area() : ${tg2.area()}`);
        console.dir(tg2);
    </script>
</body>
</html>

 

** 실행결과

 

3) 클래스를 이용한 객체의 생성(ECMA6부터 추가된 방법)

① 첫번째 방법

   class 클래스 이름 {
       constructor(매개변수1, 매개변수2, ... ) {
           프러퍼티이름1 = 값1;
           프러퍼티이름2 = 값2;
           ...
       }

       메소드이름(매개변수1, 매개변수2, ... ) {  }
   }
   const 객체이름 = new 클래스이름(값1, 값2, ... );

 

② 두번째 방법
   const 변수명 = class {
       constructor(매개변수1, 매개변수2, ...) {
           프러퍼티이름1 = 값1;
           프러퍼티이름2 = 값2;
           ...
       }
       메소드이름(매개변수1, 매개변수2, ... ) {  }
   }
   const 객체이름 = new 변수명(값1, 값2, ... );

 

** 5_클래스.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>클래스</title>
</head>
<body>
    <h2>클래스</h2>
    <script>
        'use strict';
        let Dog = class {
            // 객체를 만들기 위한 필드를 constructor에 만들어 준다.
            constructor(name, color, age) {
                this.name = name;
                this.color = color;
                this.age = age;
            }
            // 메소드는 constructor에 바깥에 만들어 준다.
            play() {
                console.log(`${this.name}가 눕습니다.`);
            }
        }

        const rucy = new Dog('루시', 'white', 9);
        console.log(rucy);
        console.log(rucy.name);
        console.log(rucy.color);
        console.log(rucy.age);
        rucy.play();
        rucy.name = '똥개';
        console.log(rucy.name);
    </script>
</body>
</html>

 

** 실행결과

 

 

5. 프로토타입(prototype)
 : 자바스크립트의 모든 객체는 프로토타입이라는 객체를 가지고 있다.

   모든 객체는 그들의 프로토타입으로 부터 프러퍼티와 메소드를 상속받는다.

   이처럼 자바스크립트의 모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받으며,

   이 때 상속되는 정보를 제공하는 객체를 프로토타입이라고 한다.
   
   [예] tg1 <-- Object.prototype
                    triangle.prototype

   [템플릿 역할] 객체를 만들때 객체의 틀과 같은 뜻
                     생성자가 객체의 틀을 만들기 위해 만들어진 함수이고 그 안에 프러퍼티 정의된 형태가 템플릿이다.
                     그 내용을 가지고 있는 객체가 프로토타입이다.

 

** 3_프로토타입(1).html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프로토타입 - 1</title>
</head>
<body>
    <h2>프로토타입 - 1</h2>
    <script>
        'use strict';
        function Dog(name, color, age){
            this.name = name;
            this.color = color;
            this.age = age;
        }

        const rucy = new Dog('루시', 'white', 9);

        // 생성자를 통해서 family와 breed의 프러퍼티는 생성하지 않았다.
        // 따라서, family는 undefined 출력되고
        //         breed는 Uncaught TypeError: rucy.breed is not a function 에러 발생
        console.log(rucy);
        console.log(rucy.name);
        console.log(rucy.color);
        console.log(rucy.age);
        //console.log(rucy.family);   // undefined
        //console.log(rucy.breed());  // 에러 : Uncaught TypeError: rucy.breed is not a function

        const ppomi = new Dog('뽀미', 'white', 4);

        // rucy 객체에 family와 breed의 프러퍼티를 추가
        rucy.family = '포메리안'
        rucy.breed = function(){
            return this.color + ' ' + this.family;
        }

        console.log(rucy);
        console.log(rucy.name);
        console.log(rucy.color);
        console.log(rucy.age);
        console.log(rucy.family);
        console.log(rucy.breed());

        console.log(ppomi);
        console.log(ppomi.name);
        console.log(ppomi.color);
        console.log(ppomi.age);

        // 잊지말자!
        // rucy 객체에 family와 breed의 프러퍼티를 추가했을뿐
        // Dog 생성자와 무관하고 Dog 생성자를 통해 객체를 생성한 ppomi에도 영향이 없다.
        //console.log(ppomi.family);  // undefined
        //console.log(ppomi.breed()); // 에러 : Uncaught TypeError: ppomi.breed is not a function
    </script>
</body>
</html>

 

** 실행결과

** 4_프로토타입(2).html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프로토타입 - 2</title>
</head>
<body>
    <h2>프로토타입 - 2</h2>
    <script>
        function Dog(name, color, age){
            this.name = name;
            this.color = color;
            this.age = age;
            //this.family = '포메리안';
        }
        
        // 이건 3_프로토타입(1) 예제와는 달리
        // 직접 생성자의 프로퍼티를 추가한 것임!
        Dog.prototype.family = '포메리안';
        Dog.prototype.breed = function(){
            return this.color + ' ' + this.family;
        }
        
        const rucy = new Dog('루시', 'white', 9);
        const ppomi = new Dog('뽀미', 'brown', 4);

        console.log(rucy);
        console.log(rucy.name);
        console.log(rucy.color);
        console.log(rucy.age);
        console.log(rucy.family);
        console.log(rucy.breed());

        console.log(ppomi);
        console.log(ppomi.name);
        console.log(ppomi.color);
        console.log(ppomi.age);
        console.log(ppomi.family);
        console.log(ppomi.breed());
    </script>
</body>
</html>

 

** 실행결과

 

 

6. 내장 객체
1) Math 객체
 : Math 객체는 수학에서 자주 사용하는 상수와 함수들을 미리 구현해 놓은 자바스크립트 표준 내장 객체

 

** Math 객체 메소드
   min() : 인수로 전달 받은 값 중에서 가장 작은 수를 리턴한다.

            인수가 전달되지 않으면 Infinity를 리턴한다.

            또한 비교할 수 없는 값이 포함되어 있으면 NaN(Not a Number)을 리턴한다.
   max() : 인수로 전달 받은 값 중에서 가장 큰 수를 리턴한다.

             인수가 전달되지 않으면 -Infinity를 리턴한다.

             또한 비교할 수 없는 값이 포함되어 있으면 NaN을 리턴한다.
   round() : 인수로 전달 받은 값을 소수점 첫번째 자리에서 반올림하여 그 결과를 리턴한다.
   floor() : 인수로 전달 받은 값과 같거나 작은 수 중에서 가장 큰 정수를 리턴한다.
   ceil() : 인수로 전달 받은 값과 같거나 큰 수 중에서 가장 작은 정수를 리턴한다.
   random() : 0보다 크거나 같고 1보다 작은 무작위의 소수를 리턴한다.

 

** 6_Math객체.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <h2>Math 객체</h2>
    <script>
        'use strict';
        // Math.min() : 인수로 전달 받은 값 중에서 가장 작은 수를 리턴
        // Math.max() : 인수로 전달 받은 값 중에서 가장 큰 수를 리턴
        console.log(Math.min());
        console.log(Math.min(1, 10, -10, 1000, 0));
        console.log(Math.min(1, 10, -10, "-1000", 0));
        console.log(Math.min(1, 10, -10, "문자열", 0));
        console.log(Math.max());

        // Math.round() : 인수로 전달 받은 값을 소수점 첫번째 자리에서 반올림하여 그 결과를 리턴
        console.log(Math.round(10.49));
        console.log(Math.round(10.5));
        console.log(Math.round(-10.5));
        console.log(Math.round(-10.51));

        // Math.floor() : 인수로 전달 받은 값과 같거나 작은 수 중에서 가장 큰 정수를 리턴
        console.log(Math.floor(10.49));
        console.log(Math.floor(10.5));
        console.log(Math.floor(-10.5));
        console.log(Math.floor(-10.51));

        // Math.ceil() : 인수로 전달 받은 값과 같거나 큰 수 중에서 가장 작은 정수를 리턴
        console.log(Math.ceil(10.49));
        console.log(Math.ceil(10.5));
        console.log(Math.ceil(-10.5));
        console.log(Math.ceil(-10.51));

        // Math.random() : 0보다 크거나 같고 1보다 작은 무작위의 소수를 리턴
        const rm = Math.random();   // 0 ~ 0.999999999 ...
        console.log(rm);

        // 문제
        // 1 ~ 10 랜덤한 자연수 출력하기
        console.log(parseInt(rm * 10) + 1);     // 내 코드
        console.log(Math.floor(rm * 10) + 1);   // 강사님 코드

        // 1 ~ 45 랜덤한 로또 번호 만들기
        let lotto = Math.random();
        lotto = Math.floor(lotto * 45) + 1
        console.log(`로또 번호 : ${lotto}`);
    </script>
</body>
</html>

 

** 실행결과


2) String 객체
 : 자바스크립트에서 문자열을 손쉽게 만들 수 있는 객체이다. 또한 문자열을 손쉽게 다룰 수 있다.

 

   const str = 'JavaScript';
   const strObj = new String('JavaScript');

 

   (str == strObj);    // true
   (str === strObj);  // false

 

   // 문자열의 길이는 length 프러퍼티에 저장됩니다.
   console.log(str.length);  // 10

 

** String 객체 메소드
   indexOf() : 특정 문자나 문자열이 처음으로 등장하는 위치를 리턴한다.
   chatAt() : 특정 문자열에서 전달 받은 인덱스에 위치한 문자를 리턴한다.
   includes() : 특정 문자열에서 전달 받은 문자열이 포함되어 있는지 여부를 리턴한다.
   substring() : 전달받은 시작 인덱스부터 종료 인덱스 바로 앞까지 문자열을 추출하여 새로운 문자열을 리턴한다.
   substr() : 전달받은 시작 인덱스부터 전달받은 개수만큼 문자열을 추출하여 새로운 문자열을 리턴한다.
   split() : 구분자를 기준으로 나눈 후 나뉜 문자열을 하나의 배열에 저장한다.
   replace() : 원본 문자열의 일부를 전달받은 문자열로 치환한다.
   trim() : 문자열의 앞뒤 공백을 제거한다.
   toUpperCase() : 영문자 중 소문자를 모두 대문자로 변환한다.
   toLowerCase() : 영문자 중 대문자를 모두 소문자로 변환한다.

'웹_프론트_백엔드 > 프론트엔드' 카테고리의 다른 글

과제-주민등록번호 검증 페이지 작성  (0) 2020.09.25
2020.09.20  (0) 2020.09.22
보강(2020.09.12, 2020.09.13)  (0) 2020.09.12
2020.08.30  (0) 2020.08.30
2020.08.29  (0) 2020.08.29