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;
}
}
특징> 인스턴스는 객체에 포함된다고 볼 수 있다.
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++;
}
}
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');
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']);
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메소드라고 한다. 클래스 자체에 할당되었기에 클래스의 인스턴스를 통해서는 호출될 수 없으며 클래스를 통해 호출해야한다.
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];
}
}
참고>