ES? ES5와 ES6

김금동·2021년 11월 14일
0

javascript

목록 보기
2/2

ES는 EcmaScript의 줄임말이다.
Ecma International이라고 여러 산업들의 표준을 정하는 기관이 있는데 여러 표준중 하나인 Ecma-262규격에 따르는 표준화된 자바스크립트 언어를 말한다.

그래서 이런 표준을 따른 언어가 여러가지 있다.
액션스크립트, J스크립트 그리고 우리가 흔히 쓰는 자바스크립트가 그 예이다.
이런 언어들이 최대한 Ecma스크립트와 호환하게 만들면서 Ecma의 규격에는 포함되지 않는 기능을 제공한다. 그래서 그런 기능들에서 각각의 언어들의 차이가 발생하는 것이다.

2009년에 만들어진 ES5와
2015년에 만들어진 ES6의 차이를 알아보기 위해
ES6에 추가된 문법을 기준으로 es5문법과 코드로 비교해보자

w3s에서 정리된 es6에서 추가된 문법들:https://www.w3schools.com/js/js_es6.asp#mark_global_methods
ecma-262깃허브:https://github.com/tc39/ecma262

1.let,const keyword
2.Arrow function
3.for/of
4.Class
5.Promise
6.Symbol
7.Default parameter
8.function rest parameter
9.String.inclues()/.startsWith()/.endsWith()
10.Array.from()/.keys()/.find()/.findIndex()
11.New Math Methods
12.New Number Properties, Methods
13.New Global Methods
14.Iterable Object.entries
15.Javascript Module

1.let,const keyword

//------ 재선언 재할당의 차이--------

//var는 재선언, 재할당가능
var a = 1;
var a = 2;
a = 3;

// let은 재할당만 가능
let b = 1;
//let b = 2; Identifier 'b' has already been declared
b = 3;

// const는 둘다 불가능
const c = 1;
//const c = 2; Identifier 'c' has already been declared
//c = 3; Assignment to constant variable.


//-------- 호이스팅의 차이 ----------

// var는 호이스팅 되지만 선언과 초기화는 되고, 할당은 안됨
console.log(a); //undefined 로 값나옴
var a = 1;

// let은 호이스팅 되지만 선언만 되고 초기화 할당은 안됨
console.log(b); // Cannot access 'b' before initialization
let b = 1;

// const는 호이스팅 되지만 선언만 되고 초기화 할당은 안됨
console.log(c); //Cannot access 'c' before initialization
const c = 1;


//------------- 스코프의 차이 --------------

//var는 블록 레벨 스코프에서는 접근가능하지만 함수 레벨 스코프에서는 접근 불가능
{
  var a = 1;
}
function funcVar() {
  var b = 1;
}

console.log(a); // 1
funcVar();
console.log(b); //b is not defined


// let은 블록,함수 레벨 스코프 둘다 접근 불가능
{
  let a = 1;
}
function funcLet() {
  let b = 1;
}
console.log(a); //a is not defined
funcLet();
console.log(b); //b is not defined


// const도 블록,함수 레벨 스코프 둘다 접근 불가능
{
  const a = 1;
}
function funcConst() {
  const b = 1;
}
console.log(a); //a is not defined
funcConst();
console.log(b); //b is not defined

2.Arrow function

//this의 관점에서 본 차이점

const test = {
  name: "sik",
  fn: function (goodList) {
    // const that = this
    goodList.forEach((good) => {
      //arrow함수의 this는 이 method를 소유한 객체를 가리킨다 (바로 상위 스코프로 결정)
      console.log(this); //{ name: 'sik', fn: [Function: fn] }
      console.log(this.name + "want buy " + good); //sikwant buy computer ,sikwant buy tv
    });
  },
};
test.fn(["computer", "tv"]);

const test2 = {
  name: "sik",
  fn: function (goodList) {
    const that = this;
    //this바인딩해야함
    goodList.forEach(function (good) {
      // 여기서의 this는 전역객체
      // 일반 함수의 this는 바인딩된 this를 찾을 때까지 상위스코프로 올라가다가 전역객체까지 가는 것이다
      console.log(that); //{ name: 'sik', fn: [Function: fn] }
      console.log(that.name + "want buy " + good); // sikwant buy computer, sikwant buy tv
    });
  },
};
test2.fn(["computer", "tv"]);

3.for/of

const iterable = ["1", "2", "3", "4"];

const iterable2 = "1234";

const iterable3 = new Map();
iterable3.set({ name: "apple" }, "fruits");
iterable3.set({ name: "banana" }, "fruits");
iterable3.set({ name: "lion" }, "animal");

const iterable4 = new Set();
iterable4.add("1");
iterable4.add("2");
iterable4.add("3");
iterable4.add("4");

for (variable of iterable) {
  console.log(variable); // 1 2 3 4
}
for (variable of iterable2) {
  console.log(variable); // 1 2 3 4
}

for (variable of iterable3) {
  console.log(variable);
  // [ { name: 'apple' }, 'fruits' ]
  // [ { name: 'banana' }, 'fruits' ]
  // [ { name: 'lion' }, 'animal' ]
}

for (variable of iterable4) {
  console.log(variable); // 1 2 3 4
}

4.Class

// ---------------es6식 class를 이용한 객체 생성--------------
class User {
  // 객체 초기화
  constructor(name) {
  //여기서의 this는 instance
    this.name = name;
    console.log(name);
  }
  //   method 만들기

  //   prototype에 method생성 (개추)
  //   sayHi() {
  //     console.log(`hi ${this.name}`);
  //   }

  // instance에 method생성 (instance하나하나의 method를 만들어 메모리 많이 잡아먹으므로 비추)
  sayHi = () => {
    console.log(`hi ${this.name}`);
  };
}

const me = new User("guemdong"); // guemdong
console.log(me); // User { name: 'guemdong' }
me.sayHi(); // hi guemdong


// ------------es5식 function을 이용한 객체 생성 --------------
function User(name) {
  //  객체 초기화
  // 여기서의 this도 instance를 나타냄
  this.name = name;
  console.log(name);
  //  method 만들기

  //   //   instance에 method생성  여기서의 this는 만들어진 인스턴스를 가리키기 때문에 이렇게 쓰면 인스턴스하나하나의 메소드가 되므로 메모리 많이 잡아먹음 (비추)
  //   this.sayHi = function () {
  //     console.log(`hi ${this.name}`);
  //   };
}
// // 직접 prototype에 메소드를 넣어줘야 메모리 안잡아먹음 이 방식이 개추
User.prototype.sayHi = function () {
  console.log(`hi ${this.name}`);
}; // 안에 method추가 class일때나 function일때나 똑같이 추가됨

const me = new User("guemdong"); // guemdong
console.log(me); // User { name: 'guemdong' }
me.sayHi(); // hi guemdong

5.Promise (활용 수정 필요)

-------promise를 써서 1초 뒤 done나오고 1초뒤 rd나오게 하기 ------------------
let promise = new Promise((resolve) => {
  setTimeout(() => resolve("done!"), 1000);
});

promise
  .then((res) => console.log(res))
  .then(() => setTimeout(() => console.log("rd"), 1000));


-------promise안 쓰고 1초 뒤 done나오고 1초뒤 rd나오게 하기----------
setTimeout(() => {
  sayDone("done");
  setTimeout(() => sayDone("rd"), 1000);
}, 1000);

function sayDone(say) {
  console.log(say);
}

6.Symbol(활용 좀 더 고민하고 쓰자)
7.Default parameter

function add2(a = 1) {
  return function (b = 3) {
    return a + b;
  };
}

function add(a = 1, b = 3) {
  return a + b;
}
console.log(add()); //4
console.log(add(1, 3)); //4

//a값 무시
console.log(add(undefined, 3)); //4
console.log(add2()(3)); //4

8.function rest parameter

------------------ 나머지 매개변수 -----------------
function add(...args) {
  let sum = 0;
  // args가 [1,2,3]이 되므로 array methods 사용가능
  for (let arg of args) sum += arg;
  return sum;
}

let x = add(1, 2, 3);
console.log(x);


------------------- 'arguments'변수---------------
function add() {
  let sum = 0;
  //arguments는 iterable한 객체이므로 array methods를 사용할 수 없음
  for (let arg of arguments) sum += arg;
  return sum;
}
let x = add(1, 2, 3);
console.log(x);

9.String.inclues()/.startsWith()/.endsWith()

10.Array.from()/.keys()/.find()/.findIndex()

11.New Math Methods

12.New Number Properties, Methods

13.New Global Methods

14.Iterable Object.entries

15.Javascript Module

profile
나원래chu해

0개의 댓글