ES5/ES6 문법 차이?

BirdsOnTree·2022년 7월 27일
0

WIL

목록 보기
2/9
post-thumbnail

ECMAScript

JavaScript가 넷스케이프 커뮤니케이션즈로부터 개발되고 나서, MS에서 JScript를 개발하였다.

하지만 두 언어는 서로 호환되지 못하는 경우가 있어 크로스 브라우징 이슈가 발생하였다.

크로스 브라우징 이슈

:기능이 모든 브라우저에서 동일하게 동작하지 않는 이슈

이 크로스 브라우징 이슈를 해결하기 위해 JavaScript를 표준화를 했다. 그게 바로 ECMAScript 이다


ES5 / ES6

let car_name = 'Ionic';
let price = 50000000;
console.log("차의 이름은 " + car_name + "이고, 가격은 " + price + "원 입니다.");
차의 이름은 Ionic이고, 가격은 50000000원 입니다.
let car_name2 = 'EV';
let price2 = 50000000;
console.log(`차의 이름은 ${car_name2}이고, 가격은 ${price2}원 입니다.`)
차의 이름은 EV이고, 가격은 50000000원 입니다.

화살표 함수

ES5

function str(arg1, arg2) { console.log(ar1, arg2); }
var str = function(arg1, arg2) { console.log(arg1, arg2); };

ES6

var str2 = (arg1, arg2) => {
  console.log(arg1, arg2);
};
var str3 = arg1 => console.log(arg1);

화살표 함수에서 인자가 하나밖에 없다면, 괄호를 생략할 수 있다.

또한 한줄로 표현이 가능하다면, 중괄호도 생략할 수 있다.


this

ES5의 경우 객체 내에 있는 메소드를 실행 할 시 this는 메소드가 선언된 해당 객체를 가르키게 된다.

하지만, 객체 안에서 선언된 함수의 this는 해당 객체가 아닌 window를 바라보고 있기 때문에 함수 안에서 this.price을 하여도 아무값도 나오지 않는다.

var NewCar = {
     name : "Ionic3",   
     price : 330000000,
     info : function() {
          console.log(this)
          console.log(this.name , this.price)

          function innerInfo() {
              console.log(this)
              return this.name + ":" + this.price
          }
          return innerInfo()
     }
}

결과로는

{name: "Ionic3", price: 330000000, info: ƒ}

Ionic3 330000000

// Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

// ":undefined"

ES6의 경우에는 this는 자신을 둘러싸고 있는 this를 바라보고 있기 때문에 바인딩이나 변수에 담을 필요가 없다.

let NewCar2 = {
     name : "EV3",   
     price : 330000000,
     info() {
          console.log(this)
          console.log(this.name , this.price)

          innerInfo = () => {
              console.log(this)
              return this.name + ":" + this.price
          }
          return innerInfo()
     }
}

결과로는

{name: "EV3", price: 330000000, info: ƒ}

EV3 330000000

{name: "EV3", price: 330000000, info: ƒ}

"김현진:25"

화살표 함수를 사용하면 함수가 선언된 스코프에 자동 바인딩이 된다.

let some_car = {
  price: 3500000,

  show: function () {
    console.log(this.price); //3500000

    
    function show_01 () {
      console.log(this.price); // undefined
    }
    show_01();

      
    //화살표 함수
    let show_02 = () => {
      console.log(this.price); // 3500000
    }
    show_02();
  }
}
some_car.show();
3500000
undefined
3500000

변수 선언

ES5에서는 var밖에 존재하지 않았지만, ES6에서는 let과 const가 추가되었다.

let은 한번 선언된 변수에 다른 값으로 바꿔줄수있지만 const는 바꿀수 없다.

또한 let, const는 블록 스코프로서 스코프 밖에서는 변수를 참조할 수 없다.

var:

재선언, 재할당 가능

block scope 외부에서 내부 참조 가능

function scope 외부에서 내부 참조 불가능

let:

재선언 불가능, 재할당 가능

block scope 외부에서 내부 참조 불가능

function scope 외부에서 내부 참조 불가능

const:

재선언 불가능, 재할당 불가능

block scope 외부에서 내부 참조 불가능

function scope 외부에서 내부 참조 불가능


모듈

ES5 이전에는 각 기능별로 JS파일을 나누고 개발 및 관리하는 것이 불가능했다.

ES6에서는 import/export 로 모듈을 관리할 수 있다.

로드 모듈

import 'import to loadname' from 'path'
export default 'module'
import Carousel from "./carousel";
cosnt carousel = new Carousel();
	export default class Carousel {
		constructor() {
		this.calc();
	}
	calc() {
		console.log(10);
	}
}

여러 모듈을 사용할 때

 import {a1, a2, ...} from '파일 경로'}
	export const i = 10;

	export function multi(x) {
		return i * x;
	}

	export function superMulti(x) {
		return i * x * 10;
	}
import * as ‘쓰고싶은단어’ form ‘path’

클래스

ES5에서는 class라는 키워드가 없었지만, 프로토타입을 통해 실현이 가능했다.

var Add = function(arg1, arg2) {
  this.arg1 = arg1;
  this.arg2 = arg2;
};

Add.prototype.calc = function() {
  return this.arg1 + "+" + this.arg2 + "=" + (this.arg1 + this.arg2);
};

var num = new Add(12, 33);
console.log(num.calc()); // 12 + 33 = 45
12+33=45

ES6에서는 class 키워드를 사용해서 선언할 수 있다.

class Multiple {
  constructor(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
  }
  calc() {
    return this.arg1 + "*" + this.arg2 + "=" + (this.arg1 * this.arg2);
  }
}

var result = new Multiple(2, 10);
console.log(result.calc()); // 2 * 10 = 20
2*10=20

클래스 상속

클래스의 상속과 오버라이딩은 super를 사용해서 할 수 있다.

ES5

	var AddSquare = function(arg1, arg2) {
		Add.call(this, arg1, arg2);
	};

	Object.assign(AddSquare.prototype, Add.prototype);

	AddSquare.prototype = {
		calc: function() {
     // 메소드는 생략될 수 없습니다.
		Add.prototype.calc.call(this);
	},
	calcSquare: function() {
		this.pow = Math.pow(this.arg1 + this.arg2, 2);
		return "(" + this.arg1 + "+" + this.arg2 + ")^2=" + this.pow;
	}
};

var numSquare = new AddSquare(5, 8);
console.log(numSquare.calc()); // 5 + 8 = 13
console.log(numSquare.calcSquare()); // (5 + 8) ^ 2 =169
class AddSquare extends Add {
	constructor(arg1, arg2) {
	super(arg1, arg2);
	}
	calc() {
		super.calc();
		}
	calcSquare() {
		this.pow = Math.pow(this.arg1 + this.arg2, 2);
		return "(" + this.arg1 + "+" + this.arg2 + ") ^ 2 =" + this.pow;
		}
	}

	var numSquare = new AddSquare(5, 8);
	console.log(numSquare.calc()); // 5 + 8 = 13
	console.log(numSquare.calcSquare()); // (5 + 8) ^ 2 = 169

0개의 댓글