Javascript ES6 class 와 모듈

2022. 10. 27. 10:32Javascript es6

C++ 에서 넘어온 문법

클래스는 미리 선언해 두었다가 클래스 선언문의 이름 앞에 new 키워드를 붙여 호출하여
인스턴스를 생성하여 사용한다. 이때 클래스 안의 this 키워드는 생성된 인스턴스를 참조한다

1.선언

 class 클래스명{

 }
 let dog = new 클래스명(); // 클래스의 첫문자는 주로 대문자로 설정하는 관습이 있다

1-1. 생성자 함수

  • 클래스의 인스턴스 생성 시에 한번 호출되는 함수. 내부 구문에 의해서 호출할 수 없다
  • constructor (정해진 함수명) 키워드를 사용하여 선언하고 function을 붙이지 않는다
  • 주로 변수의 초기화에 사용된다.
class Display{
    constructor(x=10,y=20){
        this.x = x;
        this.y = y;
        console.log(this.x,this.y);
    }
}

const display = new Display(100,200);
const display2 = new Display('이순신','최순실');
const display3 = new Display();

console.log(display.x);
console.log(display.y);

display.x = 1000;
console.log(display.x);

1-2 프로토타입 메서드

  • 인스턴스를 통해서 호출 가능한 함수.
  • 클래스 선언문 블록 내부에 선언하고, function을 붙이지 않는다
class Display{
    foo(){
        console.log(this,'foo 메서드 호출되었습니다');
    }
    foo2(x,y){
        console.log(x,y,'foo2 메서드 호출되었습니다');
    }
}

const display = new Display();
display.foo();
display.foo2('홍길동',200);

1-3 상속

  • class 자식클래스 extends 부모클래스명{  }
class Parent{
    constructor(){
        console.log('부모 생성자 함수 호출');
    }
}

class Son extends Parent{ // extends 뒤에 부모 클래스명을 작성한다
    constructor(){
        super(); // 부모 클래스의 생성자 함수 호출 없을시 에러
        console.log('자식 생성자 함수 호출');
    }
}

const parents = new Parent(); // '부모 생성자 함수 호출'

const son = new Son(); // '부모 생성자 함수 호출' ,'자식 생성자 함수 호출'

1-4 super() 키워드를 이용한 부모 클래스 메서드 호출

class Display{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
    logPosition(){
        console.log(this.x,this.y) // 100 200
    }
}

class Son extends Display{
    constructor(x,y,width,height){
        super(x,y);
        this.width = width;
        this.height = height;
    }
    logScale(){
        super.logPosition(); // 자식클래스 안에서 부모클래스의 함수를 호출할 시 super. 을 붙여준다
        console.log(this.width,this.height); // 300 400
    }
}

const son = new Son(100,200,300,400);
son.logScale();
son.logPosition(); // 외부에서 부모클래스의 함수를 호출할 때 자식클래스 의 함수로 호출이 가능하다.

console.log(son.x, son.y, son.width, son.height)

1-5 상속 예시

  • 부모 클래스의 프로토타입 메서드명 과 자식 클래스의 프로토타입 메서드 명이 같을 때 호출시 자식 클래스의 메서드를 우선으로 호출한다.
  • ex) 부모 클래스의 프로토타입 메서드는 전역, 자식클래스의 프로토타입 메서드는 지역 변수와 비슷한 맥락으로 사용된다.
class Animal{
    constructor(){
        console.log('동물입니다');
    }
    eat(){
        console.log('먹기');
    }
    sound(){
        console.log('소리');
    }
}

class Dog extends Animal{
    constructor(){
        super();
    }
    sound(){
        super.sound();
        console.log('멍멍')
    }
    eat(){
        super.eat();
        console.log('사료')
    };
    guard(){
        console.log('집지키기')
    }
}

class Tiger extends Animal{
    constructor(){
        super();
    }
    sound(){
        super.sound();
        console.log('어흥');
    }
    eat(){
        super.eat();
        console.log('닭고기');
    }
    attack(){
        console.log('사냥')
    }
}

const dog = new Dog();
dog.sound();
dog.eat();
dog.guard();

const tiger = new Tiger();
tiger.sound();
tiger.eat();
tiger.attack();

2.모듈

  • -코드의 재사용성을 높인다
  • export , import
  • <script type="module"> 을 추가해야 한다

2-1 기본값 사용(default) - 함수명이 없다

// 동일 경로의 JS 파일
export default ()=>{
    console.log('module import!');
}
/!--동일 경로의 html 파일--/
<script type="module">
    import 함수명 from './module.js';

    함수명();
</script>

2-2 함수명이 있는 함수 사용

// 동일 경로의 JS 파일
export{area,round};

let x = 10;
let y = 20;

let area = ()=>{
    return x*y;
}
let round = ()=>{
    return (x+y)*2;
}
/!-- 동일경로의 html 파일 --/
<script type="module">

    import foo from './module.js';
    import {area,round} from './module1.js';
    
    
    foo();
    console.log(area(),round());
</script>

2-3 javascript_es6_module 파일 참조

 

2-4 SPA ( Single Page Application )

html 파일이 하나로 JS로 태그를 작성해 export 한것을 html 로 import 한다.

<!-- 동일경로 HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{margin: 0; padding:0}
        #user, #user2, #user3{width: 90%; margin: 0 auto;}
        div img{width: 100%; margin-bottom:20px ;}
        div dt{text-align: center; font-size: 2em; font-weight: bold; margin-bottom: 20px;}
        div dd{line-height: 1.5em; margin-bottom: 20px;}
    </style>
</head>
<body>
    <div id="user"></div>
    <div id="user2"></div>
    <div id="user3"></div>

<script type="module">
import str from './module1.js';
import {content,content2} from './module2.js';
str();
content();
content2(2);

</script>

</body>
</html>
// 동일경로 module1 js 파일
export default ()=>{
    let str = `
    <img src="./images/a1.jpg" alt="">  
    <dl>   
     <dt>Avatar : The Way of Water</dt>
     <dd>is finally nearing its cinematic debut. The long-anticipated sequel to James Cameron's record-breaking Avatar has managed to hold firm to its final release date.</dd>
     <dd>The first teaser arrived online in May, reintroducing us to the beautiful world of Pandora as well as confirming the title was revealed alongside the first teaser trailer</dd>
    </dl>`;
     document.getElementById('user').innerHTML = str;
}
// 동일경로 module2 js 파일
export{content,content2};

let content = ()=>{
    let str = `
    <img src="./images/a2.png" alt="">  
    <dl>   
     <dt>Avatar : Na'vi</dt>
     <dd>The Na'vi (English: The People) are a race of sapient extraterrestrial humanoids who inhabit the lush jungle moon of Pandora.</dd>
    </dl>`;

     document.getElementById('user2').innerHTML = str;
}

let content2 = (cnt)=>{
    let str = `
    <img src="./images/a${cnt}.png" alt="">  
    <dl>   
     <dt>Avatar : Human</dt>
     <dd>Humans are a sapient, bipedal mammalian species native to Earth,
     who by the 22nd century has become a technologically advanced species capable of interstellar travel and colonization.</dd>
    </dl>`;

     document.getElementById('user3').innerHTML = str;
}

 

'Javascript es6' 카테고리의 다른 글

javascript es6 비구조할당과 함수  (0) 2022.10.26
JS es6  (0) 2022.10.25