본문 바로가기
JavaScript

JavaScript(화살표 함수, 객체, 프로토타입, Math/String함수)

by code2772 2022. 11. 7.

[ 목차 ]

    728x90
    반응형

    ✔ 함수 표현식

    const hello = function(){
        console.log(`안녕하세요 자바!`);
    }

    hello();


    화살표 함수
    - ECMA Script6에 추가된 문법
    - function 키워드를 사용하여 함수를 만드는 것보다 간단하게 표현
    - 화살표 함수는 항상 익명

    const hello() = () => {
        console.log(`안녕하세요 자바!`);   
    }

    const hello = () => console.log(`안녕하세요 자바!`);


    매개변수가 있는 경우
    const sum = function(x, y){
        console.log(`두 수의 합 : ${x + y});
    }

    const sum = (x, y) => console.log(`두 수의 합 : ${x + y});


    리턴값이 있는 경우
    const result = function(x,y){
        let sum =0;
        for(let i=x; i<=y; i++){
            sum += i;
        }
        return sum;
    }

    const result = (x, y) =>{
        let sum =0;
        for(let i=x; i<=y; i++){
            sum += i;
        }
        return sum;
    }


    const pow = x => x * x; // return 값이 없어도 사용이 가능하다.


    node.js 다운로드 방법! 
    node.js - .https://nodejs.org/en/ -> LTS 다운로드

     

    const func1 = () => console.log('안녀와세요 javascript!');

    func1();

    const func2 = (x,y) => console.log(`두수의 합 ${x+y}`);

    func2(10,3);

    const func3= (x) =>x*x;
    const result = func3(4);
    console.log(`4의 제곱 : ${result}`); //4의 제곱 : 16

    const func4 = (x,y) => {
        let sum =0;
        for(let i=x; i<=y;i++){
            sum+=i;
        }
        return sum;
    }
    const total = func4(1,100);
    console.log(total);//5050

    const age = 20;
    const isAdult = (age >18) ? ()=> console.log(`성인입니다.`) : () => console.log("미성년입니다.");
    // 함수 자체가 저장이 가능하다 - 화살표 함수를 사용하여 ->
    isAdult();

     객체(Object)
    프로피티(property)
    - 이름과 값으로 구성된 정렬되지 않은 집합
    - 프로퍼티는 함수도 저장할 수 있음(프로퍼티 메소드)

        const userid = {`no` : 1, `name` : `김사과`, `age` : 20, `gender` :`여자`} 



    객체를 생성하는 방법
    1. 리터럴 표기법
        const 객체명 = {
            프로퍼티명1 : 값1,
            프로퍼티명2 : 값2,
            ...
            프로퍼티명n:function(){
                프로퍼티 메소드가 호출되면 실행할 문장;
                ... 
            }
        } // 하나의 객체만을 사용하기에 적합하다



    2. 생성자를 이용
        function 생성자명(매개변수1, 매개변수2 ..){
            this.프로퍼티명1 = 값1;
            this.프로퍼티명2 = 값2;
            ...
            this.프로퍼티명n = function(){
                프로퍼티 메소드가 호출되면 실행할 문장;
                ...
            }
        } // 똑같은 객체를 여러개 사용할 때 적합하다.

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

    - new 연산자를 사용하여 객체를 생성하고 초기화 할 수 있음
    - 객체를 생성할 때 사용하는 함수를 생성자라고 함
    - 새롭게 생성되는 객체를 초기화하는 역할
    - 같은 형태의 객체를 초기화하는 역할



    3. 클래스를 이용

        const 클래스명 = class {
            constructor()매개변수1, 매개변수2...){
                this.프로퍼티명1 = 값1;
                this.프로퍼티명2 = 값2;
            ...
            }
            메소드명(매개변수1, 매개변수2){
                메소드가 호출되면 실행할 문장;
                ...
            }
        }

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


    - ECMA Script6에 추가된 객체 생성 방법
    - 내부적으로 생성자를 이용한 객체 생성 방법과 동일하게 작동

     

    //리터럴 표기법
    const dog ={
        name :'luccy',
        age:12,
        color:`white`,
        weight :3.5,
        birthday: `20091210`,
        // 프로퍼티 메소드
        gerBirthday : function(){
            return this.birthday;
            // 값은 함수자체가 저장되어있다.
        }
    }

    console.log(dog.name);
    console.log(dog.age);
    console.log(dog.color);
    console.log(dog.weight);

    console.log(dog[`name`]);
    console.log(dog[`age`]);
    console.log(dog[`color`]);
    console.log(dog[`weight`]);


    for (let i in dog){
        console.log(`i: ${i}, dog[i] : ${dog[i]}`)
    //     i: name, dog[i] : luccy
    //     i: age, dog[i] : 12
    //     i: color, dog[i] : white
    //     i: weight, dog[i] : 3.5
    }

    console.log(dog.gerBirthday());

    console.log(`---------------------`);

    // 생성자를 이용한 객체

    function Dog(name, color){
        this.name = name;
        this.color = color;
        this.play = function(){
            return `${this.name}는 놉니다.`;
        }
    }

    const Rucy = new Dog(`루시`, `white`);
    console.log(Rucy.name);
    console.log(Rucy.color);
    console.log(Rucy.play());

    const PPomi = new Dog(`뽀미`, `black`);
    console.log(PPomi.name);
    console.log(PPomi.color);
    console.log(PPomi.play());


    console.log(`---------------------`);

    //클래스를 이용환 객체생성
    const Dog2 = class{
        constructor(name,age, color){
            this.name = name;
            this.age = age;
            this.color = color;
        }
        paly(){
            return `${this.name}는 즐겁게 놉니다.`
        }
    }
    const PPory = new Dog2('뽀리', 4, 'white');
    console.log(PPory.name);
    console.log(PPory.age);
    console.log(PPory.color);
    console.log(PPory.paly());


    ✔ 상속 
    - 자바스크립트는 프로토타입 기반의 객체 지향 언어(클래스 기반의 객체지향 언어와 다름)
    - 현재 존재하고 있는 객체의 프로토타입을 사용하여 해당 객체를 복사하고 재사용하는 것

    ✔ 프로토타입(prototype)
    - 모든 객체는 프로토타입이라는 객체를 가지고 있음
    - 모든 객체는 프로토타입으로부터 프로퍼티와 프로퍼티 메소드를 상속받음
    - 모든 객체는 최소한 하나이상의 다른 객체로부터 상속을 받으며 상속되는 정보를 제공하는 객체를 프로토타입이라고 함

        const dog = new Dog();  // Dog.prototype, Object.prototype 


    function Dog(color, name, age){
        this.color =color;
        this.name = name;
        this.age=age;
    }

    const Rucy = new Dog(`white`, `lucy`, 13);
    console.log(`이름 : ${Rucy.name}`)
    console.log(`색상 : ${Rucy.color}`)
    console.log(`나이 : ${Rucy.age}`)
    Rucy.family = `포메`; // 본인 객체에 프로토타입을 생성하였기 때문에 자기에게만 변경이 되고 다른 곳에서는 포함되지 않는다.
    Rucy.getFamily = function(){
        return this.family;
    }

    console.log(`종 : ${Rucy.family}`)
    console.log(Rucy.getFamily())

    const PPomi = new Dog(`black`, `뽀미`, 4)
    console.log(`이름 : ${PPomi.name}`)
    console.log(`색상 : ${PPomi.color}`)
    console.log(`나이 : ${PPomi.age}`)
    console.log(`종 : ${PPomi.family}`)
    // console.log(PPomi.getFamily())

    console.log(`----------------------------------`);

    Dog.prototype.birthday = `20091210`;
    Dog.prototype.run = function(){
        return this.name + '달립니다.';
    } // 앞으로 객체를 만들때마다 prototype에 만들어 주었기 때문에 이 후 객체들은 이 내용이 포함된 상태이다.

    const PPory = new Dog(`white`, `bory`, 6)
    console.log(`이름 : ${PPory.name}`)
    console.log(`색상 : ${PPory.color}`)
    console.log(`나이 : ${PPory.age}`)
    console.log(`생일 : ${PPory.birthday}`)
    console.log(PPory.run())



    ✔ Math 객체
    수학에서 자주 사용하는 상수와 함수들을 미리 구현한 자바스크립트 표준 내장 객체
    min() : 가장 작은 수를 리턴. 매개변수가 전달되지 않으면 Infinity를 리턴. 비교할 수 없는 값이 포함되어 있으면 NaN을 리턴
    max() : 가장 큰 수를 리턴. 매개변수가 전달되지 않으면 -Infinity를 리턴. 비교할 수 없는 값이 포함되어 있으면 NaN을 리턴
    round() : 소수점 첫번째 자리에서 반올림하여 그 결과를 리턴
    floor() : 소수점 버림
    ceil() : 소수점 올림
    random() : 0보다 크거나 같고 1보다 작은 무작위 소수를 리턴



    console.log(Math.min());
    console.log(Math.max());
    console.log(Math.min(1,10,-10,1000,0));
    console.log(Math.min(1,10,-10,'마이너스십',0));
    console.log(Math.max(1,10,-10,'1000',0));

    console.log(Math.round(10.49));
    console.log(Math.round(10.5));
    console.log(Math.round(-10.5));
    console.log(Math.round(-10.51));

    console.log(Math.floor(10.49));
    console.log(Math.floor(10.5));
    console.log(Math.floor(-10.5));
    console.log(Math.floor(-10.51));

    console.log(Math.ceil(10.49));
    console.log(Math.ceil(10.5));
    console.log(Math.ceil(-10.5));
    console.log(Math.ceil(-10.51));

    const rn = Math.random();
    console.log(rn);
    const num = Math.floor(Math.random() * 10) + 1;
    console.log(num);



    ✔ String 객체
    문자열을 손쉽게 다룰 수 있는 객체

    const str1 = 'javascript';
    const str2 = new String('javascript');

    str1 == str2 // true
    str1 === str2 // false

    length : 문자열의 길이를 반환하는 프러퍼티
    indexOf() : 특정 문자나 문자열이 처음으로 등장하는 위치를 리턴
    charAt() : 특정 문자열에서 전달 받은 인덱스에 위치한 문자를 리턴
    includes() : 특정 문자열에서 전달 받은 문자열이 포함되어 있는지 여부를 리턴
    substring() : 전발 받은 시작 인덱스부터 종료 인덱스 바로 앞까지 문자열을 추출
    substr() : 전달 받은 시작 인텍스부터 전달 받은 개수만큼 문자열을 추출
    split() : 구분자를 기준을 나눈 후 나뉜 문자열을 하나의 배열에 저장
    replace() : 원본 문자열의 일부를 전달 받은 문자열로 치환
    trim() : 문자열의 앞 뒤 공백을 제거
    toUpperCase() : 모두 대문자로 변환
    toLowerCase() : 모두 소문자로 변환


    const str1 = '안녕하세요 JavaScript!';
    console.log(str1);;
    console.log(str1.length);

    console.log(str1.indexOf('J'));
    console.log(str1.indexOf('Java'));
    console.log(str1.indexOf('j')); // -1 찾는게 없으면
    console.log(str1.indexOf('a')); // 동일한게 있으면 가장 앞에있는 것
    console.log(str1.lastIndexOf('a'));// 가장 뒤

    console.log(str1.charAt(7));

    console.log(str1.includes('Java')); // t
    console.log(str1.includes('java')); // f

    console.log(str1.substring(7)); // 7부터 끝까지
    console.log(str1.substring(7, 11)); // 1~(11-1) 까지

    console.log(str1.substr(7,4)); //뒤에 숫자 4자리만 7부터

    const str2 =  '김사과,오렌지,반하나,이메론,배애리,채리'
    const students = str2.split(','); // 배열로 저장하게 한다.
    console.log(students)

     for(let s in students){ // 배열이니깐 사용이 가능하다.
        console.log(s, students[s]);
     }

    console.log(str1.replace('안녕하세요', 'Hello'));

    const str3 = '                 JavaScript                    ';

    console.log(`👺${str3}👺`);
    console.log(`👺${str3.trim()}👺`);



    반응형