[JS] ES6 Classes, Setters and Getters, Static Methods, Object.create

Hyodduru ·2021년 12월 28일
0

JavaScript

목록 보기
51/60

강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)

ES6 Classes

Class는 사실 "특별한 함수"이다. 함수를 함수 표현식과 함수 선언으로 정의할 수 있듯이 class 문법도 class 표현식과 class 선언 두 가지 방법을 제공한다.
Constructor function 위에 얹어진 Syntactic sugar이라고도 불린다. JavaScript자체가 Class를 갖고 있는 것이 아니라, Class는 constructor을 사용한 프로토타입 상속을 이용하기 때문이다.

class expression

const Person = class{
constructor(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  }
}

class declaration

class PersonCl {
  constructor(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  }

  //Methods will be added to .prototype property
  calcAge() {
    console.log(2037 - this.birthYear);
  }
  greet() {
    console.log(`Hey ${this.firstName}`);
  }
}

const jessica = new PersonCl('Jessica', 1996);
console.log(jessica);
jessica.calcAge(); //41
console.log(jessica.__proto__ === PersonCl.prototype); // true

PersonCl.prototype.greet = function () {
  console.log(`Hey ${this.firstName}`);
};
jessica.greet(); //Hey Jessica

Class 특징
1. Class는 호이스팅이 되지 않는다. (declaration에서도 마찬가지)
2. Classes are first-class citizens -> class를 function의 인자로 전달할 수도 있고, function에서 return할 수도 있다.
3. Class는 strict mode내에서 실행된다.

Setters and Getters

객체의 프로퍼티는 두 종류로 나뉜다.
첫 번째 종류는 데이터 프로퍼티(data property)이다. 지금까지 사용한 모든 프로퍼티는 데이터 프로퍼티이다.
두 번째는 접근자 프로퍼티(accessor property) 라 불리는 새로운 종류의 프로퍼티입니다. 접근자 프로퍼티의 본질은 함수인데, 이 함수는 값을 획득(get)하고 설정(set)하는 역할을 담당한다. 그런데 외부 코드에서는 함수가 아닌 일반적인 프로퍼티처럼 보인다.

const account = {
  owner: 'jonas',
  movements: [200, 530, 120, 300],

  get latest() {
    return this.movements.slice(-1).pop();
  },
  set latest(mov) {
    this.movements.push(mov);
  },
};

console.log(account.latest); // 300 get values. 함수 모양으로 생겼어도 
//함수를 부르지 않는다는 점 유의할 것! 함수가 아닌 property 이므로!
// 모든 set은 딱 하나의 parameter를 필요로 한다.

account.latest = 50;
console.log(account.movements); //[200, 530, 120, 300, 50]

class PersonCl {
  constructor(fullName, birthYear) {
    this.fullName = fullName;
    this.birthYear = birthYear;
  }

  //Instance methods
  //Methods will be added to .prototype property
  calcAge() {
    console.log(2037 - this.birthYear);
  }
  greet() {
    console.log(`Hey ${this.fullName}`);
  }

  get age() {
    return 2037 - this.birthYear;
  }

  //Set a property that already exists
  set fullName(name) {
    if (name.includes(' ')) this._fullName = name;
    else alert(`${name} is not a full name!`);
  }
  get fullName() {
    return this._fullName;
  }

  //Static method
  static hey() {
    console.log('Hey there ✋🏻');
    console.log(this);
  }
}


const jessica = new PersonCl('Jessica Davis', 1996);
console.log(jessica.age); //41

console.log(jessica.fullName); // Jessica Davis

const walter = new PersonCl('Walter white', 1965);
//PersonCl {_fullName: 'Walter white', birthYear: 1965}

PersonCl.hey(); // this는 PersonCl 전체를 가리킨다.

요약 및 유의사항)

  • get은 특정 값을 return해주며, set은 특정 값을 설정해준다.
    get을 통해 값을 구하거나 set을 통해 값을 설정할 때 함수를 부르지 않는다는 점 유의할 것! ex)PerconCl.age / PerconCl. age = 40;
    set에는 하나의 parameter 반드시 있어야 한다는 점 유의할 것!
  • set 함수 이름과 동일한 set property를 설정하면 계속해서 set을 실행하게 된다. constructor function과 set의 property 이름을 다르게 설정해줄 것!
    ex) set의 property 이름을 this._fullName로! => class의 properties : _fullName, birthYear

Static Methods

정적 메서드는 특정 constructor에 관련된 함수이다. 그렇기에 클래스의 인스턴스(객체) 없이 호출이 가능하며 클래스가 인스턴스화되면 호출할 수 없다.
constructor function 또는 class와 관련하여 주로 사용이 된다.

ex) Array.from() 에서 from은 Array constructor자체에 있는 methods. (not to the prototype of the constructor) 그렇기에 from()을 일반 array에는 사용할 수 없다.

ex) Number.parseFloat(12); //12
parseFloat()는 Number constructor에 있는 method. 일반 숫자에는 사용되지 않는다.

Constructor function에서 static method 만들기

Person.hey = function () {
  console.log('Hey there ✋🏻');
  console.log(this); //entire constructor function(Person) 이 함수를 부르고 있는게 정확히 Person 자체 이므로.
};
Person.hey(); //Hey there ✋🏻
// jonas.hey(); 불가능 inherited되지 않았으므로!

Class 내에서 만들 때에는 method 앞에 static을 적어주면 된다.

Object.create

object의 prototype을 수동적으로 설정을 해준다.
Object.create(prototype) 형태.

const PersonProto = {
  calcAge() {
    console.log(2037 - this.birthYear);
  },
  init(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  },
};

const steven = Object.create(PersonProto);
console.log(steven);
steven.name = 'Steven';
steven.birthYear = 2002;
steven.calcAge(); //35

console.log(steven.__proto__ === PersonProto); // true

const sarah = Object.create(PersonProto);
sarah.init('Sarah', 1979);
sarah.calcAge(); //58

prototype chain이 일어난다.
constructor function에서는 자동적으로 constructor function으로부터 만들어진 object에 prototype에 대한 link가 생기는 반면, Object.create에서는 직접 객체의 prototype을 설정해준다는 특징이 있다.
하지만 둘다 결국 같은 Prototype chain, prototypal inheritance 발생한다. Object.create가 자주 사용되는 방법은 아니다.

profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글