코어자바스크립트 7장 part2 (ES5 ES6)

KHW·2021년 3월 9일
0

코어자바스크립트

목록 보기
17/19

ES5

 	var ES5 = function(name){
        	this.name = name;
        };
        ES5.staticMethod = function(){
        	return this.name + ' staticMethod';
        };
        ES5.prototype.method = function(){
        	return this.name + ' method';
        }
        var es5Instance = new ES5('es5');
        console.log(ES5.staticMethod());	//ES5 staticMethod
        console.log(es5Instance.method());	//es5 method

ES6

 	var ES6 = class{
        	constructor (name){
        		this.name = name;
        	}
        	static staticMethod(){
        		return this.name + ' staticMethod';
        	}
        	method = function(){
        	return this.name + ' method';
        	}
        }

        var es6Instance = new ES6('es6');
        console.log(ES6.staticMethod());	//ES6 staticMethod
        console.log(es6Instance.method());	//es6 method

ES5의 생성자함수 => ES6의 class내에서 constructor
ES5의 메서드 => ES6의 static 메서드
ES5의 prototype.메서드 => ES6의 프로토타입 메서드


클래스 상속(ES6)

var Rectangle = class{
  constructor(width, height){
    this.width = width;
    this.height = height;
  }
  getArea(){
    return this.width * this.height;
  }
};

var Square = class extends Rectangle{
  constructor(width){
    super(width,width);
  }
  getArea(){
    console.log('size is:',super.getArea());
  }
};

에서

let square = new Square(10);
square.getArea();

를 실행하면 결과는 size is: 100이 나온다.
이전 내용에서처럼 class를 사용하지않은 따로 뭘 연결하고 별짓을 안해도 된다.


출처

코어자바스크립트

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글