본문 바로가기

분류 전체보기37

JavaScript 기초(29)_클래스(4) static 1. static 변수, 함수 : 객체가 아닌, 클래스의 변수와 함수 다음의 코드를 보자. class A { static age = 31; static hello(){ console.log(A.age); } } console.log(A); console.log(A.age); A.hello(); [Running] [class A] { age: 31 } 31 31 클래스 A를 출력했을 때, [] 안에 클래스 이름이 나오며 {} 안에는 변수와 값이 출력된다. A.age로 접근하여 출력했을 때도 31이 정상 출력되며 A.hello()로 hello() 함수에 접근하여도 31이 정상 출력된다. 그렇다면 위 코드에서 'static'을 제거하면 어떻게 될까? class B { age = 31; hello(){ cons.. 2021. 10. 26.
JavaScript 기초(28)_클래스(3) get과 set 1. get과 set 아래의 코드를 통해서 get과 set의 쓰임을 알아보자. class A { _name = 'no name'; get name(){ return this._name + '@@@'; } set name(value){ this._name = value + '!!!' } } const a = new A(); console.log(a); a.name = 'Kim'; console.log(a); console.log(a.name); console.log(a._name); Running] A { _name: 'no name' } A { _name: 'Kim!!!' } Kim!!!@@@ Kim!!! 맨 먼저 클래스 A를 가지는 객체 a를 생성해주었다. 그대로 a를 출력했을 때는 초기값으로 설정된 .. 2021. 10. 25.
JavaScript 기초(27)_클래스(2) property 1. 멤버 변수 (객체의 프로퍼티) 우선, 생성자(constructor)를 통해서 프로퍼티를 다음과 같이 할당할 수 있다. class A { constructor(name, age){ this.name = name; this.age = age; } } console.log(new A('Kim', 31)); [Running] A { name: 'Kim', age: 31 } 조금 더 간단한 방법은 없을까? 다음 코드를 살펴보자. class B { name = 'Kim'; age = 31; } [Running] B { name: 'Kim', age: 31 } 위와 같이 바로 'name' 과 'age'를 할당하는 방법이다. 그렇다면 아래와 같은 코드는 어떻게 작동할까? class C { name = 'no na.. 2021. 10. 24.
JavaScript 기초(26)_클래스(1) constructor 1. 클래스 : 객체를 만들 수 있는 새로운 방법 클래스를 만드는 방식은 크게 2가지가 있다. 첫 번 째는 선언적 방식이다. 아래의 코드를 참고하자 class A {} console.log(new A()); [Running] A {} class로 직접 선언하는 방식이며 출력할 때는 'new'를 덧붙여 함수를 호출하듯이 활용하면 된다. 두 번 째는 변수에 할당하는 방식이다. const B = class {}; console.log(new B()); [Running] B {} 변수 B에다가 클래스를 할당하여 위와 같이 출력하였다. 선언적 방식으로 표현이 가능하다면 클래스에는 과연 호이 스팅이 일어날까? new C(); class C {} Running] new C(); ^ ReferenceError: Can.. 2021. 10. 23.