JS 클래스

진성대·2023년 3월 28일
0

Front-End

목록 보기
6/15

클래스

function user(first, last) {
  this.firstName = first;
  this.LastName = last;
}

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

const sungdae1 = new user('sungdae', 'jin');
const amy1 = new user('Amy', 'Clarke');
const neo1 = new user('Neo', 'Smith');

console.log(amy1.getFullName());
console.log(neo1.getFullName());
console.log(sungdae1.getFullName());

prototype

  • JavaScript는 클래스라는 개념이 없다. 그래서 기존의 객체를 복사하여(Cloning) 새로운 객체를 생성하는 프로토 타입 기반 언어다.
  • 프로토타입 기반 언어는 객체 원형인 프로토타입을 이용하여 새로운 객체를 만들어 낸다.
  • 이렇게 생성된 객체 역시 다른 객체의 원형이 될 수 있다.
  • 프로토타입은 객체를 확장하고 객체 지향적인 프로그래밍을 할 수 있게 해준다.
  • 프로토 타입은 크게 두가지로 해석되는데 객체를 참조하는 prototype 속성과 객체 맴버인 proto속성이 참조하는 숨은 링크가 있다.

This

  • 일반(Normal)함수는 호출 위치에 따라 this를 정의한다.

  • 화살표(Arrow)함수는 자신이 선언된 함수 범위에서 this를 정의한다.

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

const amy3 = {
  name: 'Amy',
  normal: sungdae2.normal,
  arrow: sungdae2.arrow
}
amy3.normal();
amy3.arrow();

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

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

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

const sungdae4 = new User2('Sungdae');
sungdae4.normal();
sungdae4.arrow();

화살표 함수를 사용할 예제

ex) 타임 함수

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

ES6 Classes

  • function 대신 class를 사용하여 객체 정의
class User {
  constructor(first, last){
    this.firstName = first;
    this.lastName = last;
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

const sungdae = new User('sungdae', 'jin');
const amy = new User('Amy', 'Clarke');
const neo = new User('Neo', 'Smith');

console.log(sungdae);
console.log(amy.getFullName());
console.log(neo.getFullName());

상속

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

const myVehicle = new Vehicle('운송수단', 2);
console.log(myVehicle);

class Bicycle extends Vehicle {
  constructor(name, wheel) {
    super(name, wheel);
  }
}

const myBicycle = new Bicycle('삼천리', 2);
const daugtersBicycle = new Bicycle('세발', 3);

console.log(myBicycle);
console.log(daugtersBicycle);

class Car extends Vehicle {
  constructor(name, wheel, license) {
    super(name, wheel);
    this.license = license;
  }
}

const myCar = new Car('벤츠', 4, '1종 보통');
const yourCar = new Car('bmw', 4, '2종 보통');

console.log(myCar);
console.log(yourCar);
profile
신입 개발자

0개의 댓글