자바스크립트

 

 

인프런 :  모던 자바스크립트(javascript) 개발을 위한 ES6 강좌

 

1. 모던 자바스크립트 개발을 위한 ES6 강좌 소개

javascript 표준을 정의하는 ECMAScript 중 최근 가장 중요한 변화를 겪었던 ECMAScript 2015(이하 ES6) 를 학습해볼 수 있는 강좌입니다. ES6 에서 새롭게 추가된 syntax 와 기능들을 코드를 통해서 짚어보고 사용해 보면서 javascript 의 이런저런 특징들을 알 수 있게 됩니다. 또한 학습 중간 중간 '배열만들기' 와  '로또번호만들기' 등의 간단한 실습 예제들을 만들어, 생각해보면서 자기의 것으로 만들 수 있도록 도와주는 실습형 강좌입니다.

 

 

자바스크립트 테스트 사이트

1) https://jsbin.com/?html,js,console

 

2 ) https://codepen.io/pen/

 

 

소스 :  https://github.com/braverokmc79/javascript-modern-ES6

 

 

scope

 

1.let

 

강의  :  https://www.inflearn.com/course/es6-강좌-자바스크립트/unit/6975?tab=curriculum

 

var name = "global var";

function home() {
    var homevar = "homevar";
    for (let i = 0; i < 100; i++) {

    }
    //console.log(i);

    if (true) {
        let myif = "myif";
    }

    console.log(myif);
}

home();

 

 

 

 

2.let 과 closure

강의  클릭

 

<!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>
        li{
            list-style: none; 
            border: 1px solid #eeee;
            padding: 10px;
            width: 200px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    
    <div>
        <ul>
            <li>javarcirpt</li>
            <li>java</li>
            <li>python</li>
            <li>django</li>
        </ul>
    </div>

<script>
    var list =document.querySelectorAll("li");
    // for(var i=0; i<list.length; i++){
    //     list[i].addEventListener("click", function(){
    //         console.log(i +"번째 리스트입니다.");
    //     });
    // }클로저(closure)는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것
       // var 변수 사용시 외부에 함수 i값이 누적되어 " 4번째 리스트입니다." 출력
    // =>
    for(let i=0; i<list.length; i++){
        list[i].addEventListener("click", function(){
            console.log(i +"번째 리스트입니다.");
        });
    }

</script>


</body>
</html>

 

 

 

 

3.const - 선언된 변수 지키기

강의  클릭

 

// function home() {
//     var homename = "my house";
//     homename = "your house";
//     console.log(homename);
// }

function home() {
    const homename = "my house";
    homename = "your house";
    console.log(homename);
}
//const 를 기본으로 사용한다.
//그런데 변경이 될 수 있는 변수는 let을 사용한다.
//var 는 사용하지 않는다.



home()

 

 

 

 

4.const 특성과 immutable array

강의  클릭

function home() {
    const list = ["apple", "orange", "watermelon"];
    list.push("banana");
    console.log(list);
}

//const 를 사용하더라도 배열과 오브젝트의 값을 변경하는 것은 가능하다.
home();



//immutable array 를 어떻게 만들지?
const list = ['apple', "orange", "watermelon"];
list2 = [].concat(list, "banana");
console.log(list === list2);



 

 

 

 

String

 

5.ES2015 String 에 새로운 메서드들

강의클릭

//ES2015 string 에 새로운 메서들.

let str = "hello world ! ^^ ~~";
let matchstr = "^ ~~";

console.log(str.startsWith(matchstr));
console.log(str.endsWith(matchstr));
console.log("includes  test :", str.includes("world"));


 

 

 

Array

 

6.for of - 순회하기

강의클릭

var data = [1, 2, undefined, NaN, null, ""];
for (var i = 0; i < data.length; i++) {
    console.log(data[i]);
}

data.forEach(function (value) {
    console.log(value);
});

//object 사용, array 에서는 사용하지 않는다.
//문제점 for in 을 사용시 자신가지고 있지 않는 상위 객체 까지 출력
//Array.protoype.getIndex =function(){};
for (let idx in data) {
    console.log(data[idx]);
}

console.log("배열 출력 for of :");
for (let value of data) {
    console.log(value);
}

console.log("str for of==> 문자열도 문자 단위로 출력 가능");
var str = "hello world !!!";
for (let value of str) {
    console.log(value);
}





 

 

 

 

 

7.spread operator - 배열의 복사

강의클릭

//spread operator, 펼침연산자

let pre = ["apple", "orange", 100];
let newData = [...pre];
console.log(pre, newData);
console.log(pre === newData);

 

 

 

8.spread operator - 몇가지 활용

강의클릭

 

let pre = [100, 200, "hello", null];
let newData = [0, 1, 2, 3, ...pre, 4];
console.log(newData);


function sum(a, b, c) {
    return a + b + c;
}
let pre2 = [100, 200, 300];

console.log("전개 연산자 이전 apply 사용 : ", sum.apply(null, pre2));

console.log("전개 연산자 :", sum(...pre2));

 

 

 

 

9.from 메서드로 진짜 배열 만들기

강의클릭

function addMark() {
    //let newData = [];

    // for (let i = 0; i < arguments.length; i++) {
    //     newData.push(arguments[i] + "!");
    // }
    //가짜 배열을 from  통해 진째 배열로 만든다.
    let newArray = Array.from(arguments);
    let newData = newArray.map(function (value) {
        return value + "!";
    })
    console.log(newData);
}

addMark(1, 2, 3, 4, 5, 6, 7, 8, 9);

 

 

 

 

 

실습 1 - 특정 문자열이 포함된 배열 만들어 반환하기

 

10.실습 예제1

강의클릭

<!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>
</head>
<body>
    <ul>
        <li>apple</li>
        <li>orange</li>
        <li>banana</li>
        <li>strawberry</li>
    </ul>
    
<script>
function print(){
    /*
        filter, includes, from 을 사용해서 문자열 'e' 가 포함된 노드로
        구성된 배열을 만들어서 반환하기
    */

}

print();
</script>

</body>
</html>

 

 

 

 

 

11.실습 예제 1 풀어보기

강의클릭

<!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>
</head>
<body>
    <ul>
        <li>apple</li>
        <li>orange</li>
        <li>banana</li>
        <li>strawberry</li>
    </ul>
    
<script>
function print(){
    /*
        filter, includes, from 을 사용해서 문자열 'e' 가 포함된 노드로
        구성된 배열을 만들어서 반환하기
    */

    const li=document.querySelectorAll("li");
    
    console.log("li : " , toString.call(li));

    const newArr=Array.from(li).filter(item=>{  
        console.log(item.innerText);
       return item.innerText.includes("e")   
    });
    
    
    console.log(" ================");
    newArr.forEach((element, index) => {
        console.log("newArr : ",index, element.innerText);
    });
}

print();
</script>

</body>
</html>

 

 

 

 

 

 

Object

12.간단히 객체생성하기

강의클릭

const name = "crong";
const age = 33;

const obj = {
    name: name,
    age: age
}
//console.log(obj);



function getObj() {
    let name = "crong";

    const getName = function () {
        return name;
    }

    const setName = function (newname) {
        name = newname;
    }

    const printName = function () {
        console.log(name);
    }

    return {
        getName,
        setName
    }
}
var obj2 = getObj();
console.log(obj2.setName(11));
console.log(obj2.getName());
console.log(obj2.printName);



 

 

 

 

 

Destructuring (구조 분해 할당)

13.Destructuring Array (배열 분해하기)

강의클릭

let data = ["crong", "honux", "jk", "jinny"];
// let jisu = data[0];
// let jung = data[2];


let [jisu, , jung] = data;
console.log(jisu, jung);


crong jk

 

 

 

14.Destructuring Object

강의클릭

let obj = {
    name: "crong",
    address: "Korea",
    age: 10
}

let { name, age } = obj;
console.log(name, age);


let { name: myName, age: myAge } = obj;
console.log(myName, myAge);

 

 

 

 

15.Destructuring 활용 JSON파싱

강의클릭

var news = [
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },

    {
        "userId": 2,
        "id": 2,
        "title": "2222sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "2222quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
]

let [obj1] = news;
// let { title } = obj1;
// console.log(title);

let { title, body } = news[1];
console.log(title, body);


 

 

 

 

16.Destructuring 활용_Event객체전달

강의클릭

var news = [
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },

    {
        "userId": 2,
        "id": 2,
        "title": "2222sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "2222quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
];


function getNewsList([, { title }]) {
    console.log(title);
}

getNewsList(news);

 

 

<!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>
</head>
<body>
    
<div>sunt aut facere repellat provident occaecati excepturi optio reprehenderit</div>

<script>
    document.querySelector("div").addEventListener("click", function({target}){        
        console.log(target.tagName);
        console.log(target.innerText);
    })
</script>

</body>
</html>

 

 

 

 

 

Set & WeakSet

17.Set 으로 유니크한 배열만들기

강의클릭

let mySet = new Set();
//console.log(toString.call(mySet));

//set : 중복없이 유일한 값을 저장하려고 할때, 이미 존재하는지 체크할 때 유용.

mySet.add("crong");
mySet.add("hary");
mySet.add("crong");


console.log("==============");
mySet.forEach(function (v) {
    console.log(v);
});


console.log("==============");
console.log(mySet.has("crong"));

mySet.delete("crong");


console.log("==============");
mySet.forEach(function (v) {
    console.log(v);
});

 

 

 

 

 

 

18.WeakSet 으로 효과적으로 객체타입저장하기

강의클릭

//weakset
//참조를 가지고 있는 객체만 저장이 가능하다.
//객체형태를 중복없이 저장하려고 할때 유용하다.
let arr = [1, 2, 3, 4];
let arr2 = [5, 6, 7, 8];
let obj = { arr, arr2 };
let ws = new WeakSet();

ws.add(arr);
//ws.add(111);
// ws.add("111");
// ws.add(null);
//ws.add(function () { });
//ws.add(arr);
ws.add(obj);
arr = null;
arr2 = null;


console.log(ws);

 

 

 

 

 

 

 

map & WeakMap

 

1) Array -> Set, weakset

 

2) Object  ->  map, weakmap

 

 

 

 

 

Map & WeakMap

19.Map & WeakMap 추가정보를 담은 객체저장하기기

강의클릭

// map & WeakMap
// 1) Array -> Set, weakset
// 2) Object -> map, weakmap

//map 은 key/value

let wm = new WeakMap();
let myfun = function () { };

//이 함수가 얼마나 실행될지를 알려고 할때.

wm.set(myfun, 0);
//console.log(wm);

let count = 0;
for (let i = 0; i < 10; i++) {
    count = wm.get(myfun); //get value
    count++;
    wm.set(myfun, count);
}

//myfun 함수가 키값
console.log(wm);
console.log(wm.get(myfun));
myfun = null;
console.log(wm.has(myfun));





 

 

 

 

 

20.WeakMap 클래스 인스턴스 변수 보호하기

강의클릭

//WeakMap 활용

// function Area(height, width) {
//     this.height = height;
//     this.width = width;
// }


// Area.prototype.getArea = function () {
//     return this.height * this.width;
// }

// let myarea = new Area(10, 20);


const wm = new WeakMap();

function Area(height, width) {
    wm.set(this, { height, width });
}

Area.prototype.getArea = function () {
    const { height, width } = wm.get(this);
    return height * width;
}

let myarea = new Area(10, 20);
console.log(myarea.getArea());
console.log(myarea.height);


myarea = null;

console.log(wm.has(myarea));










 

 

 

 

 

실습예제 2 - Destructuring 과 Set 을 활용한 로또 번호 생성기

21.로또 번호 생성기

강의클릭

const SETTING = {
    name: "LUCKY LOTTO!",
    count: 6,
    maxNumber: 36
}

function getRandomNumber({ count, maxNumber }) {
    console.log(count, maxNumber);
    let mySet = new Set();
    while (true) {
        if (mySet.size === count) break;
        let result = Math.floor(Math.random() * maxNumber) + 1;
        mySet.add(result);
    }

    return mySet;
}


console.log(getRandomNumber(SETTING));

 

 

 

 

 

 

 

Template

22.Template처리

강의클릭

const data = [
    {
        name: "coffee-bean",
        order: true,
        items: ['americano', 'milk', 'green-tea']
    },
    {
        name: 'starbucks',
        order: false
    }
]

//json 으로 응담을 받고, javascript obejct 변환한 후에 어떠한 데이터 처리 조작을 한 후에 dom 에 추가
//데이터, + HTM 문자열의 결합이 필요하기 때문에,


const template = `<div>welcome ${data[0].name} !!</div>`;
console.log(template);

 

 

 

23.Tagged Template literals

강의클릭

<!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>
</head>
<body>
    

    <div id="message"></div>


<script>
    const data = [
    {
        name: "coffee-bean",
        order: true,
        items: ['americano', 'milk', 'green-tea']
    },
    {
        name: 'starbucks',
        order: false
    }
]

//json 으로 응담을 받고, javascript obejct 변환한 후에 어떠한 데이터 처리 조작을 한 후에 dom 에 추가
//데이터, + HTM 문자열의 결합이 필요하기 때문에,


function fn(tags, name, items) {
    console.log(tags);
    if (typeof items === "undefined") {
        items = "주문가능한 상품이 없습니다.";
    }

    return (tags[0] + name + tags[1] + items + tags[2]);
}

const template = fn`<div>welcome ${data[0].name} !!</div>
    <h2>주문가능항목</h2><div>${data[1].items}</div>`;


console.log(template);


data.forEach((v) => {
    let template = fn`<div>welcome ${data[0].name} !!</div>
    <h2>주문가능항목</h2><div>${data[1].items}</div>`;
    document.querySelector("#message").innerHTML += template;
})
</script>

</body>
</html>

 

 

 

 

 

function

24.Arrow function 활용

강의클릭

//arrow function

setTimeout(() => {
    console.log("setTimeout arrow");
}, 1000);

// let newArr = [1, 2, 3, 4, 5, 6].map((v) => {
//     return v * 2;
// });

let newArr = [1, 2, 3, 4, 5, 6].map((v) => v * 2);


console.log(newArr);

 

 

 

 

 

25.Arrow function 의 this context

강의클릭

//this context of Arrow function
const myObj = {
    runTimeout() {
        setTimeout(function () {
            console.log(this === window);
            this.printData();
        }, 200);
    },
  
  printData(){
    console.log("hi Codeequal");
  }
}

myObj.runTimeout();

 

여기서 this 는 window  라서 오류

화살표 함수를 사용할 경우 this 는 myObj 가리 킴

 

//this context of Arrow function
const myObj = {
    runTimeout() {
        setTimeout(()=>{
            console.log(this === window);
            this.printData();
        }, 200);
    },
  
  printData(){
    console.log("hi Codeequal");
  }
}

myObj.runTimeout();

 

//this context of Arrow function
const el =document.querySelector("p");

const myObj={
  
   register(){
    el.addEventListener("click", (evt)=>{
      this.printData();
    })
  },
  
  printData(){
    console.log("clicked");
  }
}


myObj.register();

 

 

 

 

 

26.function default paramaters

강의클릭

//default parameter

function sum(value, size) {
    size = size || 1;
    return value * size;
}
console.log(sum(3));


function sum2(value, size = 10) {
    return value * size;
}
console.log(sum2(3));


function sum3(value, size = { value: 5 }) {
    return value * size.value;
}
console.log(sum3(5));

 

 

 

 

27.rest paramaters

강의클릭

//reset parameter

function checkNum() {
    const agrArray = Array.prototype.slice.call(arguments);
    console.log(agrArray);
    console.log(toString.call(agrArray));
    const result = agrArray.every((v) => typeof v === "number");
    console.log("result : ", result);
}


//const result = checkNum(10, 2, 3, 5, 6, "555");

// ...agrArray 스프레이드 배열 매개변수가 다음과 같은 역할을 한다.
//  const agrArray = Array.prototype.slice.call(arguments);

function checkNum2(...agrArray) {
    console.log("arguments   : ", arguments);
    console.log(toString.call(agrArray));
    const result = agrArray.every((v) => typeof v === "number");
    console.log("result : ", result);
    // agrArray.map(arg => console.log(arg));
}


const result2 = checkNum2(10, 2, 3, 5, 6, "555", false);

 

 

 

 

 

객체

28.class 를 통한 객체생성

강의클릭

//Es6 class

function Health(name) {
    this.name = name;
}


Health.prototype.showHealth = function () {
    console.log(this.name + "님 안녕하세요.");
}

const h = new Health("crong");
h.showHealth();


 

=>

//Es6 class


class Health {
    constructor(name, lastTime) {
        this.name = name;
        this.lastTime = lastTime;
    }

    showHealth() {
        console.log("안녕하세요.." + this.name);
    }
}

const myHealth = new Health("crong");
myHealth.showHealth();

console.log(toString.call(Health));

 

 

 

 

 

 

29.Object assign으로 JS객체만들기

강의클릭

//Object assign 메서드.

var healthObj = {

    init: function (name, healthTime) {
        this.name = name;
        this.healthTime = healthTime;
        this.showHelth();
    },
    showHelth: function () {
        console.log("오늘 운동시간  : " + this.healthTime);
    }
}

healthObj.init("홍길동", "12:00");
console.log("-----------------");
console.log("");

const myHealth = Object.create(healthObj);
myHealth.healthTime = "11:20";
myHealth.name = "crong";
console.log(myHealth);

console.log("-----------------");
console.log("");
const myHealth2 = Object.assign(Object.create(healthObj), {
    name: "crong",
    lastTime: "11:30"
});
console.log("Object.assign myHealth2 :", myHealth2);
추

 

출력=>

오늘 운동시간  : 12:00
-----------------

{ healthTime: '11:20', name: 'crong' }
-----------------

Object.assign myHealth2 : { name: 'crong', lastTime: '11:30' 

 

 

 

 

 

 

 

30.Object assign으로 Immutable 객체만들기

강의클릭

React - 생활코딩 4 - Redux , 글 생성 , 수정,삭제 구현 Object.Assign 깊은 복사

복사 방법

처음에 빈 개열 객체  Object.assign(빈객체, 복사대상객체값, 변경할 값또는 빈객체)

 

Object.assign({}, previousObj, {

    lastTime: "12:30",

    name: "호녹스",

    age: 99

});

 

//Object assign 메서드
//객체 복사
const previousObj = {
    name: "crong",
    lastTime: "11:30"
}

const myHealth = Object.assign({}, previousObj, {
    lastTime: "12:30",
    name: "호녹스",
    age: 99
});

console.log("myHealth is : ", myHealth);
console.log("previousObj === myHealth  :", previousObj === myHealth);


const myHealth2 = Object.assign({}, previousObj, {});
console.log("previousObj === myHealth2 :", previousObj === myHealth2);

 

출력 :

myHealth is :  { name: '호녹스', lastTime: '12:30', age: 99 }
previousObj === myHealth  : false
previousObj === myHealth2 : false

 

 

 

 

30.Object setPrototypeOf로 객체만들기

강의클릭

//Object setPrototypeOf로 객체만들기

const healthObj = {
    showHealth: function () {
        console.log("오늘 운동시간 : " + this.healthTime);
    },

    setHealth: function (newTime) {
        this.healthTime = newTime;
    }
}


// const myHealth = Object.assign(Object.create(healthObj), {
//     name: "crong",
//     lastTim: "11:20"
// });


const newObj = Object.setPrototypeOf({
    name: "crong",
    lastTim: "11:20"
}, healthObj);

console.log("myHealth is", newObj);

 

myHealth is { name: 'crong', lastTim: '11:20' }

 

 

 

 

 

31.Object setPrototypeOf 로 객체간 prototype chain생성하기

강의클릭

//Object setPrototypeOf 로 객체간 prototype chain생성하기

const healthObj = {
    showHealth: function () {
        console.log("오늘 운동시간 : " + this.healthTime);
    },

    setHealth: function (newTime) {
        this.healthTime = newTime;
    }
}


//child obj
const healthChildObj = {
    getAge: function () {
        return this.age;
    }
}

//healthObj  , healthChildObj
Object.setPrototypeOf(healthChildObj, healthObj);


const childObj = Object.setPrototypeOf({
    age: 22
}, healthChildObj);


childObj.setHealth("11:55");
childObj.showHealth();

console.log("childeobj is", childObj);


 

 

 

 


 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  라이트

대부분의 여자들이 사랑 다음으로 매달리는 것이 종교 아니면 예술이다. -프란체스코 알베로니

댓글 ( 4)

댓글 남기기

작성