Learn Javascript_classes

chloe·2020년 8월 25일
0

Javascript

목록 보기
9/13

Class 클래스?

  • 객체를 만들어 내기 위한 설계도 혹은 틀
  • 연관되어 있는 변수와 메서드(행동)의 집합
    클래스는 함수이므로 함수 표현식과 함수 선언식을 사용하는 것처럼 사용가능하다.
    class는 다른 함수처럼 호이스팅을 지원하지 않는다.

Classes are a tool that developers use to quickly produce similar objects.

Although you may see similarities between class and object syntax, there is one important method that sets them apart. It’s called the constructor method. JavaScript calls the constructor() method every time it creates a new instance of a class.

class Surgeon{
  constructor(name,department){ 
  this.name=name;
  this.department=department;

  }
}

Object(객체)?

  • 소프트웨어 세계에 구현할 대상
  • 클래스에 선언된 모양 그대로 생성된 실체(클래스를 이용해서 실제로 데이터를 넣어만드는 것이 오브젝트)
    특징> 클래스의 인스턴스라고도 부른다.
    객체는 모든 인스턴스를 대표하는 포괄적인 의미를 갖는다.

Instance (인스턴스)?

  • 설계도를 바탕으로 소프트웨어 세계에 구현된 구체적인 실체
  • 즉, 객체를 소프트웨어에 실체화하면 그것을 인스턴스라고 부른다. 실체화된 인스턴스는 메모리에 할당된다.

특징> 인스턴스는 객체에 포함된다고 볼 수 있다.

An instance is an object that contains the property names and methods of a class, but with unique property values.

class Dog {
  constructor(name) {
    this.name = name;
    this.behavior = 0;
  } 
}

const halley = new Dog('Halley'); // Create new Dog instance
console.log(halley.name); // Log the name value saved to halley
// Output: 'Halley'

클래스, 객체, 인스턴스의 차이?

클래스 VS 객체

  • 클래스는 설계도, 객체는 설계도로 구현한 모든 대상

객체 VS 인스턴스

  • 클래스의 타입으로 선언되었을 때 객체라고 부르고 그 객체가 메모리에 할당되어 실제 사용될 때 인스턴스라고 부름
    -객체는 현실세계에 가깝고 인스턴스는 소프트웨어 세계에 가깝다.

    constructor(생성자)
    생성자는 클래스로 생성된 객체를 만들고 초기화하는데 쓰이는 메서드이다.
    클래스당 하나의 생성자만 가질 수 있으며 super()를 통해 부모 클래스 생성자를 호출 가능하다

getter는 어떤 속성을 얻고자 할때 사용되며, 반드시 return값이 존재해야 한다.
setter는 어떤 속성을 새로 할당하고자 할때 사용된다. 인스턴스가 생성된 후에 getter,setter를 추가해야한다면 defineGetter,defineSetter를 이용한다

ex)getter method 추가


class Dog {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  get name() {
    return this._name;// _추가한 이유는 which indicate these properties should not be accessed directly.

  get behavior() {
    return this._behavior;
  }

  incrementBehavior() {
    this._behavior++;
  }
}

Method calls

class Dog {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  get name() {
    return this._name;
  }

  get behavior() {
    return this._behavior;
  }   

  incrementBehavior() {
    this._behavior++;
  }
}

const halley = new Dog('Halley');

Inheritance

parent class called Animal

class Animal {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  get name() {
    return this._name;
  }

  get behavior() {
    return this._behavior;
  }

  incrementBehavior() {
    this._behavior++;
  }
}

Now that we have these shared properties and methods in the parent Animal class, we can extend them to the subclass, Cat

class Cat extends Animal {
  constructor(name, usesLitter) {
    super(name);
    this._usesLitter = usesLitter;
  }
}

Ex)

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
    this._certifications = certifications;
  }
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma', 'Pediatrics']);
  • The extends keyword makes the methods of the animal class available inside the cat class.
  • The constructor, called when you create a new Cat object, accepts two arguments, name and usesLitter.
  • The super keyword calls the constructor of the parent class. In this case, super(name) passes the name argument of the Cat class to the constructor of the Animal class. When the Animal constructor runs, it sets this._name = name; for new Cat instances.
  • _usesLitter is a new property that is unique to the Cat class, so we set it in the Cat constructor.

Notice, we call super on the first line of our constructor(), then set the usesLitter property on the second line. In a constructor(), you must always call the super method before you can use the this keyword — if you do not, JavaScript will throw a reference error. To avoid reference errors, it is best practice to call super on the first line of subclass constructors.

Static Methods 정적 메소드

클래스 자체에 할당된 함수를 static메소드라고 한다. 클래스 자체에 할당되었기에 클래스의 인스턴스를 통해서는 호출될 수 없으며 클래스를 통해 호출해야한다.

Sometimes you will want a class to have methods that aren’t available in individual instances, but that you can call directly from the class.

Take the Date class, for example — you can both create Date instances to represent whatever date you want, and call static methods, like Date.now() which returns the current date, directly from the class. The .now() method is static, so you can call it directly from the class, but not from an instance of the class.

class Animal {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  static generateName() {
    const names = ['Angel', 'Spike', 'Buffy', 'Willow', 'Tara'];
    const randomNumber = Math.floor(Math.random()*5);
    return names[randomNumber];
  }
} 

참고>

profile
Front-end Developer 👩🏻‍💻

0개의 댓글