절차적 프로그래밍과 객체지향 프로그래밍
컴퓨터 프로그래밍 패러다임에는 여러가지가 있는데, 객체지향 프로그래밍은 그 중 하나이다. 초기 프로그래밍 언어들은 절차적 프로그래밍 순차적 명령의 조합이었다. 절차적 프로그래밍은 코드가 길어질수록 복잡해지고 각각 코드간 의존도도 높아지는 문제가 발생하기 쉽다. 그러나, 객체지향 프로그래밍이라는 패러다임이 등장하면서 데이터 모델의 청사진(blueprint)을 만들고 데이터와 기능을 묶어 한 번에 처리할 수 있게 되었다.
//절차적(procedural) 프로그래밍: 변수들과 함수로 분리된 형태
let baseSalary = 30_000;
let overtime = 10;
let rate = 20;
function getWage(baseSalary, overtime, rate){
return baseSalary + (overTime * rate);
}
//OOP
let employee = {
baseSalary: 30_000,
overtime: 10,
rate: 20,
getWage: function(){
return this.baseSalary + (this.overtime * this.rate);
}
}
employee.getWage();
OOP의 4가지 특징
class Shape{
constructor(width,height,color){
this.width = width;
this.height = height;
this.color = color;
}
draw(){
console.log(`${color} shape!`);
}
getArea(){
return this.width * this.height;
}
}
class Rectangle extends Shape{}
//Shape 클래스로부터 상속받은 메소드를 덮어씀으로써(override) 같은 메소드가 부모클래스와 다른 기능을 수행하게 되었다.
//draw 메소드를 override하고 부모객체의 draw 메소드를 불러올 수 있다.
class Triangle extends Shape{
draw(){
super.draw();
console.log('now drawing');
getArea(){
return (this.width * this.height)/2;
}
}
class 정의하는 방법
//함수로 클래스 정의하기
//클래스 정의 함수의 첫글자는 대문자로 쓰고, 명사형으로 써서
//일반 함수의 소문자, 동사형과 구분할 수 있도록 한다.
function Student(name, age, grade, school){
this.name = name;
this.age = age;
this.grade = grade;
this.school = school;
}
//메소드 정의하기
Student.prototype.study = function(){}
Student.prototype.read = function(){}
//new 키워드로 인스턴스 객체 만들기
let senior = new Student('kim','19','A','high');
//배열을 정의하는 것은 Array의 인스턴스를 만드는 것과 동일하다
let arr = new Array ('first','second','third');
let arr = ['first','second','third'];
//클래스 키워드로 클래스 정의하기
//클래스의 이름은 ES5에서 클래스 정의함수 이름과 마찬가지로 대문자로 시작하며 명사형으로 쓴다.
class Student{
constructor(name, age, grdade, school){
this.name = name;
this.age = age;
this.grade = grade;
this.school = school;
}
//메소드 정의하기
study(){}
read(){}
}
//new 키워드로 인스턴스 객체 만들기
let senior = new Student('kim','19','A','high');
//지금까지 배열을 생성하여 요소들을 할당하고, length 속성과 push 메소드를 사용해왔다.
let arr = ['hello','world','javascript'];
arr.length; //3
arr.push('algorithm');
//배열을 정의하는 것은 Array의 인스턴스를 생성하는 것과 동일하다.
let arr = new Array('hello','world','javascript');
arr.length; //3
arr.push('algorithm');
class ES6 추가
OOP에서 말하는 클래스란, 쉽게 말하면 객체를 만드는 공장이다. 속성값이 할당되지 않고 메모리에도 올라가지 않는다.
instance (객체)
class를 바탕으로 만들어진 객체로 메모리에 올라간다.
constructor 함수
class field (데이터 멤버 또는 멤버 변수)
클래스 내부의 캡슐화된 변수를 말한다. 클래스 필드는 인스턴스의 프로퍼티가 될 수 있다. 쉽게 말해, 자바스크립트의 생성자 함수에서 this(인스턴스)에 추가한 프로퍼티를 클래스 기반 객체지향 언어에서는 클래스 필드라고 부른다.
this
new 키워드로 호출된 constructor 함수가 만든 instance 객체를 가리킨다.