[Worksheet 220426] JS 클래스

방예서·2022년 4월 26일
0

Worksheet

목록 보기
16/47
JavaScript Essentials

JS 클래스

Prototype

생성자 함수.

const heropy = {
  firstName: 'heropy',
  lastName: 'park',
  getFullName: function () {
    return `${this.firstName} ${this.lastName}`
  }
};

const neo = {
  firstName: 'neo',
  lastName: 'bang',
  getFullName: function () {
    return `${this.firstName} ${this.lastName}`
  }
};

console.log(heropy.getFullName());
console.log(neo.getFullName());

거의 똑같은 구조의 객체 데이터가 있다.

function User(first, last) {
  this.firsName = first;
  this.lastName = last;
}

위의 구조를 이런 방식으로 작성하였다.
생성자 함수를 함수와 구분하기 위해 new와 함께 Pascalcase로 작성하도록 한다.

어떤 기호만으로 특정한 과정을 거치지 않고 데이터를 작성하는 것을 리터럴 방식이라고 한다.

//생성자 함수 new user
const heropy = new User('Heropy', 'Park');
const neo = new User('Neo', 'Bang');
const amy = new Uer('Amy', 'Kim');

getFullName 함수

User.prototype.getFullName = function() {
  return `${this.firstName} ${this.lastName}`;
}

생성자 함수 내에 숨어있는 proto 라는 속성을 부르는 .prototype

this

일반 함수는 호출 위치에 따라 this 정의된다.
화살표 함수는 자신이 선언된 함수 범위에서 this 정의된다.

const heropy = {
  name: 'Heropy',
  normal: function() {
    console.log(this.name);
  },
  arrow: () => {
    console.log(this.name);
  }
}

heropy.normal(); //Heropy
heropy.arrow(); //undefined

normal()은 일반 함수라서 호출 위치(heropy.normal()) 에서 this는 자기 앞의 heropy가 this가 된다.
arrow()는 화살표 함수라서 자신이 선언된 함수 범위에서 this를 정의하는데 지금 코드에서는 this가 누구인지 아직 알 수 없다.

하단에 추가 코드를 작성했다.

const amy = {
  name:'Amy',
  normal: heropy.normal, //함수 실행 X 명시만 해준 것
  arrow: heropy.arrow
}

amy.normal(); //Amy
amy.arrow(); //undefined

이 코드에서 normal()은 역시 일반 함수이기 때문에 자신이 호출된 위치인 amy.normal()에서의 this는 자기 앞의 amy가 this가 된다.
arrow() 역시 화살표 함수인데 호출된 위치랑 상관 없이 위의 코드에서와 동일하게 undefined가 출력된다.

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

User.prototype.normal = function() {
  console.log(this.name);
}

User.prototype.arrow = () => {
  console.log(this.name);
}

const heropy = new User('Heropy');

heropy.normal(); //Heropy
heropy.arrow(); //undefined

위의 코드도 마찬가지이다.
밑의 이미지는 normal() 일반 함수의 this 정의를 그림으로 나타낸 것이다.

normal() 일반함수

const timer = {
  name: 'Heropy!',
  timeout: function () {
    setTimeout(function() {
      console.log(this.name);
    }, 2000)
  }
}

timer.timeout();

여기서 this는 누구를 가르키게 될 것이냐.
this가 들어가있는 함수가 일반 함수이므로 자신이 호출된 위치에서 this를 정의하게 되는데, setTimeout() 함수 내에는 name 같은건 없다 ... 그러니 undefined가 출력된다.

const timer = {
  name: 'Heropy!',
  timeout: function () {
    setTimeout(() => {
      console.log(this.name);
    }, 2000)
  }
}

timer.timeout();

그래서 setTimeout() 안에 함수를 화살표 함수로 정의해주었다.
그러면 이 코드에서 this는 자신이 선언된 함수 범위에서 정의하기 때문에 자신을 감싸고 있는 함수 범위에서의 this는 timer이기 때문에 제대로 동작한다.


✍ 나의 활용 목적에 따라서 일반/화살표 함수를 잘 선택해서 사용할 것!


const heropy = {
  name: 'Heropy',
  normal: function() {
    console.log(this.name);
  },
  arrow: () => {
    console.log(this.name);
  }
}

여기서 normal: function() 부분은 축약할 수 있다고 위에서 배웠다.

const heropy = {
  name: 'Heropy',
  normal() {
    console.log(this.name);
  },
  arrow: () => {
    console.log(this.name);
  }
}

어떤 이름이 나오고 소괄호, 중괄호가 연달아 나오면 일반 함수라는 것!
축약해서 사용할 수 있음을 잘 기억해두자.

ES6 Classes


function User(first, last) {
  this.firsName = first;
  this.lastName = last;
}

user.prototype.getFullName = function() {
  return `${this.firstName} ${this.lastName}`;
}

이 코드를

class User {
  constructor(first, last) {
    this.firsName = first;
    this.lastName = last;
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

이렇게 깔끔하게 정리할 수 있다.

ECMA(ES6) 에서 class라는 문법이 추가 되어 기존의 prototype으로 클래스를 만드는 것보다 쉽게 class를 정의할 수 있다.

상속(확장)

class Vehicle {
  constructor(name, wheel) {
    this.name = name;
    this.wheel = wheel;
  }
}

class Bicycle extends Vehicle {
  constructor(name, wheel) {
    super(name, wheel); //super === 확장된 클래스 Vehicle
    //상속, 확장 되어서 super의 속성을 그대로 사용할 수 있다
  }
}

class Car extends Vehicle {
  constructor(name, wheel, license) {
    super(name, wheel); //super === 확장된 클래스 Vehicle
    this.license = license; //다른 속성을 추가할 수 있다.
  }
}

확장(상속)된 클래스의 속성을 받아서 쓸 수 있다.

profile
console.log('bang log');

0개의 댓글