Prototype

100pearlcent·2021년 8월 21일
0

JavaScript

목록 보기
3/22
post-thumbnail

Prototype

상속을 구현하는 개념

함수형으로 프로그래밍하거나 OOP와 큰 관계없이 개발한다면 프로토타입은 잘 쓰이지않지만 인터널이 어떻게 작동하는지 파악할 수 있다.

// ES5 Syntax (구 문법)

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

// 프로토타입 체이닝
Student.prototype.greet = function greet() {
	return `Hello, ${this.name}`;
};

const myself = new Student('Jinju');
console.log(myself); // Student { name: 'Jinju' }
console.log(me.greet()); // Hello, Jinju!

함수를 정의하듯이 클래스를 만든다.
클래스라는 키워드가 존재하지만 실제로는 프로토타입을 기반으로 한 함수.

new 키워드를 통해 함수는 생성자(constructor) 역할을 하게 된다.

// ES5 Syntax (구 문법)

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

Person.prototype.greet = function greet() {
	return `Hello, ${this.name}`;
};

function Student(name) {
  this.__proto__.constructor(name);
};

Student.prototype.study = function study() {
	return `${this.name} is studying.`;
};

// Person과 Student 사이의 연결관계를 만드려면
Object.setPrototypeOf(Student.prototype, Person.prototype);

const myself = new Student('Jinju');
console.log(myself instanceof Student); // true
console.log(myself instanceof Person); // true

const anotherPerson = new Person('John');
console.log(anotherPerson instanceof Student);
console.log(anotherPerson instanceof Person);

ES5로 쓰인 위 코드를 신 문법으로 작성해보자

class Person {
	constructor(name) {
    	this.name = name;
    }
  
    greet() {
    return `Hi, ${this.name}`;
    }
};

class Student {
	constructor(name) {
    	super(name);
    }
  
  	study() {
    	return `${this.name} is studying`;
    }
};

const myself = new Student('Jinju');
console.log(myself.study());
console.log(myself.greet());

코드가 훨씬 깔끔해졌다~~😊

0개의 댓글