[JS] Class, Class field

Jay ·2022년 11월 15일
0

??

클래스로 인스턴스를 생성할 대 외부의 초기값으로 클래스 필드를 초기화해야한다면?
-> constructor로 필드 초기화.

Class?

객체 생성 방법.
생성자 함수. new 연산자와 함께 호출되어 인스턴스를 생성한다.

Class 정의

Why Class field?

인스턴스 프로퍼티는 반드시 constructor 내부에서 정의해야 했지만, class field를 통해 클래스 몸체에 메서드뿐만 아니라 프로퍼티를 직접 정의할 수 있게 되었다.
스택오버플로우 참고

// without class field 
class Person {
  constructor() {
    this.firstName = "Mike";
    this.lastName = "Patel";

    this.getName = () => {
      return this.firstName + " " + this.lastName;
    };
  }
}

var p = new Person();

console.log(p.firstName); // Mike
console.log(p.lastName); // Patel
console.log(p.getName); // () => { return this.firstName + " " + this.lastName; }
console.log(typeof p.getName); // function
console.log(p.getName()); // Mike Patel
// with class field 
class MyClass() {
  /* properties - do not depend on the constructor*/
  foo1 = 1;
  foo2 = 2;
  foo3 = 3;
  foo4; /* this is a property that this class will have - 
          I do not need to look at the constructor to know about it */

  /* easy to see what the constructor does that is only about *constructing* the object */
  constructor(someArg) {
    this.foo4= someArg;
  }

  /* callable field are separated from the rest of the simple properties and construction logic */
  bar1 = () => {}
  bar2 = () => {}
  bar3 = () => {}
  bar4 = () => {}
}

constructor와 properties가 분리되어, constructor가 좀 더 simplified.
혁명적인 기능은 아니지만, class를 좀 더 보기쉽게 표현해줄 수 있게 되었다.

Class Field

클래스 기반 객체지향 언어에서 클래스가 생성할 인스턴스의 프로퍼티를 가리키는 용어. 클래스 필드는 클래스 내부에서 변수처럼 사용된다.

class Person {
  name = 'Lee';
}

const me = new Person('Jung');
/// -> 정상 작동

2021년 1월 기준, TC39 프로세스의 stage3에서, 자바스크립트에서도 인스턴스 프로퍼티를 마치 클래스 기반 객체지향 언어의 클래스 필드처럼 정의할 수 있는 새로운 표준 사양 "Class field declarations"가 제안되었음.

2022년 6월 기준 ECMAscript에 정식 표준으로 승급되었음.

클래스 필드에 함수를 할당하는 것은 가능하지만, 권장되지는 않는다.
왜냐하면 그 함수는 프로토타입 메서드가 아닌 인스턴스 메서드가 되기 때문.

class Person {
	name = 'Lee';

	getName = function () {
      return this.name;
    }
}
const me = new Person();
console.log(me.getName()); // Lee

결론적으로 클래스 필드 정의 제안을 통해 JS에서 인스턴스 프로퍼티를 정의하는 방식이 두 가지가 되었다.
인스턴스 생성시 외부 초기값으로 클래스 필드를 초기화할 필요가 있다면 constructor에서 인스턴스 프로퍼티를 정의하는 기존 방식 사용.
인스턴스 생성시 외부 초기값으로 클래스 필드 초기화할 필요가 없다면 기존 방식, 클래스 필드 정의 방식 모두 사용 가능.

Private Field

#을 사용해 private field 정의.

typescript에서는 public, private, protected 모두 지원하며 의미 동일.

profile
Jay입니다.

0개의 댓글