- 화살표 함수

ECMA Script에 추가된 문법

function 키워드를 사용하여 만드는 것보다 간단하게 표현 가능하다.

화살표 함수는 항상 익명이다.

 

const 함수명 = () => {
	함수 호출시 실행할 문장;
    ...
}

 

 

1) 매개변수가 있는 경우

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

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

 

 

2) 리턴 값이 있는 경우

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

            return sum;
        }
        
        const pow = x => x * x;

 

 


화살표 함수 사용해보기!

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

console.log(func1(10,15));

const age = 10;
const isAdult = (age > 18) ? () => console.log('성인입니다!') :
console.log('미성년입니다!');

위 코드의 결과


- 객체 (Object)

프로퍼티 (Property)

이름과 값으로 구성된 정렬되지 않은 집합

프로퍼티는 함수도 저장할 수 있다. (프로퍼티 메소드)

            const userid = {
                'no' : 1,
                'name' : '김사과',
                'gender' :  '여자'
            };

 

 

- 객체를 생성하는 방법

1) 리터럴 표기법

        const 객체명 = {
            프로퍼티명1 : 값1,
            프로퍼티명2 : 값2,
            ...
            프로퍼티명n:function() {
                프로퍼티 메소드가 호출되면 실행할 문장;
                ...
            }
        }

 

 

2) 생성자를 이용

new 연산자를 사용하여 객체를 생성하고 초기화할 수 있다.

객체를 생성할 때 사용하는 함수를 생성자라고한다.

새롭게 생성되는 객체를 초기화하는 역할을 한다.

같은 형태의 객체를 여러 개 생성할 때 유리하다.

 

        function 생성자명 (매개변수1, 매개변수2 , ..) {
            this.프로퍼티명1 = 값1;
            this.프로퍼티명2 = 값2;
            ...
            this.프로퍼티명n : function() {
                프로퍼티 메소드가 호출되면 실행할 문장;
                ...
            }
        }

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

 

 

 

3) 클래스를 이용

ECMA Script6에 추가된 객체 생성 방법이다.

내부적으로 생성자를 이용한 객체 생성 방법과 동일하게 작동한다.

        const 클래스명 =  class {
            constructor(매개변수1, 매개변수2, ...){
                this.프로퍼티명1 = 값1;
                this.프로퍼티명2 = 값2;
                ...
            }

            매소드명 (매개변수1, 매개변수2 ...) {
                메소드가 호출되면 실행할 문장;
            }
        }

        const 객체명1 = new 클래스명(값1, 값2, .. );
        const 객체명2 = new 클래스명(값1, 값2, .. );
        ...

 

 

- 상속

자바스크립트는 프로토타입 기반의 객체 지향 언어이다. ( 클래스 기반의 객체 지향 언어와는 다름)

현재 존재하고 있는 객체의 프로토타입을 사용하여 해당 객체를 복사하고 재사용하는 것을 의미한다.

 

 

✔ 프로토 타입(prototype)

모든 객체는 프로토타입이라는 객체를 가지고 있다.

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

모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받으며 상속되는 정보를 제공하는 객체를 프로토타입이라고 한다.

 

        const dog = new Dog();      
        // Dog.prototype을 상속받아 생성자가 만들어짐, Object.prototype

 

 


객체 사용해보기!

// 리터럴 표기법
const dog  = {
    name : '로이',
    age :  9,
    color : 'cream',
    birthday : '20130716',
    getBirthday :  function() {
        return this.birthday;
    }
}
console.log(dog.name)
console.log(dog.age)
console.log(dog.color)
console.log(dog.getBirthday())


// 클래스 사용
const Dog2 = class{
    constructor(name,age,color,birthday) {
        this.name = name;
        this.age = age;
        this.color = color;
        this.birthday = birthday;
    }

    getBirthday() {
        return `${this.name}의 생일은 ${this.birthday} 입니다!`
    }
}

const Rucy = new Dog2('Rucy', 10, 'white', '20221012');
console.log('------------------');
console.log(Rucy.name);
console.log(Rucy.age);
console.log(Rucy.color);
console.log(Rucy.getBirthday());



// 생성자 사용
function Dog3(name,color,age) {
    this.name = name;
    this.color = color;
    this.age = age;
    this.play = function (){
        return `${this.name}는 놀아요!`
    }
} 

const dodo = new Dog3('도도', 'black', 10);

console.log('--------------------------')
console.log(dodo.name);
console.log(dodo.color);
console.log(dodo.age);
console.log(dodo.play());

위 코드의 결과

 


상속

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

// 프로토타입을 상속받아서 객체를 생성하게된다.
const Roi = new Dog('로이', 9, 'cream');

// 부모인 프로토타입을 바꾼것이 아니기 때문에 다른 객체는 쓸수 없음
Roi.family = '포메';

console.log(`이름: ${Roi.name}`)
console.log(`나이: ${Roi.age}`)
console.log(`색상: ${Roi.color}`)
console.log(`생일: ${Roi.birthday}`)    
console.log(`종: ${Roi.family}`)


// 부모인 프로토타입에 추가하기
Dog.prototype.birthday = '20130716';
Dog.prototype.run = function() {
    return this.name + '는 달립니다!';
}

const Dodo =  new Dog('도도', 10, 'black');
console.log(`도도의 생일 : ${Dodo.birthday}`);

위 코드의 결과

로이의 생일이 undefined인 이유는 출력 후에 프로토타입에 추가했기 때문이다. 로이 객체에 추가한 family는 도도에서는 쓸 수 없다. 로이와 도도 모두 쓰기 위해서는 프로토타입으로 추가해야 한다.

 

 

 

 

 

 

복사했습니다!