HANA -J

25. 클래스 본문

개발/Javascript

25. 클래스

Hana-J 2021. 11. 29. 22:32

1. 자바스크립트는 프로토타입 기반 객체지향 언어이다.

2. 프로토타입 기반 객체지향 언어는 클래스가 필요없는 객체지향 프로그래밍 언어이다.

3. ES5에서는 생성자 함수와 프로토타입을 통해 객체지향 언어의 상속을 구현할 수 있다.

var Person = (function(){
	//생성자 함수
	function Person(name) {
		this.name = name;
}
//프로토타입 메서드
Person.prototype.sayHi = function(){
	console.log(`Hi! My name is ${this.name}`);
};
//생성자 함수 반환
return Person;
}());

//인스턴스 생성
var me = new Person('Hana');
me.sayHi(); //Hi My name is hana 출력

ES6 클래스

  1. 클래스를 new 연산자 없이 호출하면 에러가 발생, 생성자 함수를 new연산자 없이 호출하면 일반 함수로서 호출
  2. 클래스는 상속을 지원하는 extends, super키워드 제공
  3. 클래스는 호이스팅이 발생하지 않은것처럼 동작, 하지만 함수선언문, 함수표현식으로 정의된 생성사 함수는 함수호이스팅 발생
  4. 클래스 내의 모든 코드에는 암묵적으로 strict mode가 지정되어 실행된다.
  5. 클래스는 함수로 평가된다.
//클래스 선언문
class Person{
	//생성자
	constructor(name) {
	this.name = name;  //인스턴스 생성 및 초기화
}
//프로퍼타입 메서드
sayHi(){
	console.log(`Hi My name is ${this.name};
}
//정적 메서드
static sayHello(){
	console.log('Hello');
 }
}
//인스턴스 생성
const me = new Person('Hana');

console.log(me.name);
me.sayHi();       //프로토타입 메서드 호출
Person.sayHello(); //정적 메서드 호출 

클래스의 인스턴스 생성과정

class Person{
	//생성자
	constructor(name) {
		//1. 암묵적으로 인스턴스가 생성되고 this에 바인딩 된다
		console.log(this); //Person {}
		console.log(Object.getPrototypeof(this) === Person.prototype);
		//2. this에 바인딩 외어 있는 인스턴스르 초기화
		this.name = name; 
		//3.완성된 인스턴스가 암묵적으로 반환
	}
}

 

 

728x90

'개발 > Javascript' 카테고리의 다른 글

클로저  (0) 2021.12.15
13. 전역변수의 문제점  (0) 2021.11.28
12. 즉시호출 함수 표현식(IIFE)와 node.js require()함수  (0) 2021.11.25
12. 함수(1)  (0) 2021.11.25
8-11장  (0) 2021.11.20
Comments