Todos (lodash, RxJS, Angular, class&constructor, getter&setter)

jungeundelilahLEE·2022년 2월 23일
0

Angular

목록 보기
2/4

lodash

  • lodash - clone deep : value를 (타입상관없이) 복사해서 완전히 새로운 변수를 만들 수 있음
  • lodash - _.isNil : 체크한다. value가 null || undefined
  • lodash - _.isNan : 체크한다. value가 NaN
  • lodash - _.isNull : 체크한다. value가 null

RxJS

  • rxjs - Subscription
  • rxjs - takeUntil (container-qty.component.ts)

Angular

  • pipe와 subscribe 연결 및 구독하는 flow
  • OnInit, OnDestroy 의 lifecycle

JS

  • class와 constructor()
  • getter setter

1. class와 constructor()

Fields

  • Public instance fields
  • Private instance fields
  • Public static fields
  • Private static fields

class
The class becomes useful when you create an instance of the class. An instance is an object containing data and behavior described by the class.
(클래스는 인스턴스를 만들 때 유용하다. 인스턴스는 클래스에서 설명하는 데이터와 동작들을 포함하는 객체이다.)
constructor()
constructor is a special method in the body of a class that initializes the instance.
That's the place where you set the initial values for the fields, or do any kind of object setup.
If you don't define a constructor for the class, a default one is created. The default constructor is an empty function, which doesn't modify the instance.
()

1) Public instance fields

class User {
  // properties - do not depend on the constructor
  age = 32;
  // easy to see what the constructor does that is only about *constructing* the object
  constructor(name) {
    name; // => 'delilah'
    this.you = name;
  }
}

const user = new User('delilah');
user // User {you: 'delilah'}
  • 여기서 youpublic field
    you 프로퍼티는 User class body 바깥에서도 접근할 수 있기 때문
    it could be difficult to grasp the fields list.
  • ageclass field
    No matter what constructor does, the instance always has the same set of fields.

????????? 다시......

2) Private instance fields

캡슐화는 클래스 내부의 세부 정보들을 숨길 수 있는 중요한 개념이다.
캡슐화된 클래스를 사용하며느 공통 인터페이스에만 접근하고 클래스의 디테일한 부분까지 연결되지 않기 때문에, 세부 정보가 변경될 시 더 쉽게 업데이트할 수 있다.
이를 위한 방법으로 private fields를 사용하는 것이다. 클래스의 외부에서는 private filed를 직접 변경할 수 없다.
The private fields are accessible only within the body of the class.

접미사 #를 사용한다.

class User {
  #name;
  constructor(name) {
    this.#name = name;
  }
  getName() {
    return this.#name;
  }
}
const user = new User('willy');
user.getName(); // 접근 가능 => 'willy'
user.#name;     // 접근 불가능 => SyntaxError is thrown

3) Public static fields

클래스 자체에 필드를 정의할 수도 있다.
상수 또는 특정한 정보를 클래스에 저장하는 데 유용하다.
static키워드를 사용한다.

class User {
  static TYPE_ADMIN = 'admin';
  static TYPE_REGULAR = 'regular';
// 위 TYPE_ADMIN과 TYPE_REGULAR는 static variables (정적 변수)를 정의한다.
  name;
  type;
  constructor(name, type) {
    this.name = name;
    this.type = type;
  }
}
const admin = new User('딜라', User.TYPE_ADMIN);
// 정적 변수를 사용하기 위해서는 [클래스명.정적변수명]과 같이 사용한다.
admin.type === User.TYPE_ADMIN; // true

4) Private static fields

정적 필드도 숨기고 싶을 때는 #필드명과 같이 사용한다.

class User {
  static #MAX_INSTANCES = 2;
  static #instances = 0;
  
  name;
  constructor(name) {
    User.#instances++;
    if (User.#instances > User.#MAX_INSTANCES) {
      console.warn('에러에러에러')
    }
    this.name = name;
  }
}
new User('헬로');
new User('봉쥬흐');
new User('안냥'); // 에러에러에러

Methods

  • Instance methods
  • Getters and setters
  • Static methods
  • 필드는 데이터를 가지고 있다.
  • 하지만, 그 데이터를 수정하는 것은 (클래스의 한 파트인 special function) 메소드에 의해 수행된다.
  • JS는 인스턴스와 정적메소드 둘 다 지원한다.

1) Instance methods

class User {
  name = 'Unknown';
  constructor(name) {
    this.name = name;
  }
  getName() {
    return this.name;
  }
}
const user = new User('delilah lee');
user.getName(); // => 'delilah lee'

In a class method, as well as in the constructor, this value equals to the class instance. Use this to access instance data: this.field, or even call other methods: this.method().

???????????? this value

class User {
  name = 'Unknown';
  constructor(name) {
    this.name = name;
  }
  getName() {
    return this.name;
  }
  nameContains(str) {
    return this.getName().includes(str);
  }
}
const user = new User('delilah lee');
user.getName(); // => 'delilah lee'
user.nameContains('lee'); // => true
user.nameContains('willy'); // => false

nameContains(str) { ... } is a method of User class that accepts one parameter str. More than that, it executes another method of the instance this.getName() to get the user's name.

???????? this.getName() is instance of User class?

메소드를 private하게 할 수도 있다.

class User {
  #name;
  constructor(name) {
    this.#name = name;
  }
  #getName() {
    return this.#name;
  }
  nameContains(str) {
    return this.#getName().includes(str);
  }
}
const user = new User('delilah lee');
user.nameContains('lee');   // => true
user.nameContains('willy'); // => false
user.#getName(); // SyntaxError is thrown

2) Getters and setters

getter는 필드 값을 얻을 때 실행
setter는 값을 설정할 때 실행

class User {
  nameValue;
  constructor(name) {
    this.name = name;
  }
  get name() {
    return this.nameValue;
  }
  set name(name) {
    if (name === '') {
      console.warn('에러에러에러')
    }
    this.nameValue = name;
  }
}
const user = new User()
user // User {nameValue: undefined}
const user = new User('') // 에러에러에러
const user = new User('이정은')
user // User {nameValue: '이정은'} => by getter
user.name = '이윌리' // => by setter
user // User {nameValue: '이윌리'}
  • get method명 ( ) { } : 값을 가져온다 / 반환값이 있음
  • set method명 (할당받을 값에 대한 매개변수 선언) { } : 값을 할당받는다
let obj = {
  name : '이정은',
  get hello() {
    console.log(this.name, '겟')
  	return this.name + '하트';
  },
  set hello(value) {
    console.log(this.name, '셋', value)
    this.name = value;
  }
}
obj
{name: '이정은'}
obj.hello
// 이정은 겟
'이정은하트'
obj.hello = '이윌리'
// 이정은 셋 이윌리
'이윌리'
obj.hello
// 이윌리 겟
'이윌리하트'
obj
{name: '이윌리'}

3) Static methods

정적 메서드는 클래스에 직접 연결된 함수이다. 따라서, 클래스의 인스턴스가 아니라, 클래스와 관련된 로직을 가진다.
static 메소드명으로 사용한다.

  • 정적 메서드는 정적 필드에 액세스할 수 있다.
  • 정적 메서드는 인스턴스 필드에 액세스할 수 없다.
class User {
  static takenNames = [];
  static isNameTaken(name) {
    return User.takenNames.includes(name);
  }
  name = 'Unknown';
  constructor(name) {
    this.name = name;
    User.takenNames.push(name);
  }
}
const user = new User('Jon Smith');
const user = new User('John Lee');
User.takenNames // ['Jon Snow', 'John Lee']
User.isNameTaken('Jon Smith');   // true

Inheritance

  • Parent constructor: super() in constructor()
  • Parent instance: super in methods

1) Parent constructor: super() in constructor()

class Child extends Parent { }
: child class는 parent class로부터 constructor, fields, methods를 상속받는다.
단, 부모클래스의 private members는 자식클래스로 상속되지 않는다.

class User {
  name;
  constructor(name) {
    this.name = name;
  }
  getName() {
    return this.name;
  }
}
class ContentWriter extends User {
  arr = [];
}
const writer = new ContentWriter('willy');
writer.name;      // => 'willy'
writer.getName(); // => 'willy'
writer.arr;     // => []

ContentWriter 클래스는 User 클래스로부터,
name라는 field와 + constructor constructor와 + getName()이라는 method를 상속받았고 + arr라는 field를 새로 선언했다.

2) Parent instance: super in methods

자식클래스에서 부모클래스의 constructor를 call하고 싶으면, 자식클래스의 constructor 내부에서 super()라는 special function을 사용해야 한다.
자식클래스 내부의 super(name)는 부모클래스의 생성자를 실행한다.

class User {
  name;
  constructor(name) {
    this.name = '이정으니';
  }
  getName() {
    return this.name;
  }
}
class Child extends User {
    constructor(name) {
        super(name);
    }
}
const dd = new Child();
dd	// Child {name: '이정으니'} 
	// name: "이정으니" [[Prototype]]: User

2) Parent instance: super in methods

자식클래스에서 부모클래스의 method에 접근하고 싶으면, super 를 사용한다.

class User {
  name;
  constructor(name) {
    this.name = '시바브라더';
  }
  getName() {
    return this.name;
  }
}
class Child extends User {
  posts = [];
  constructor(name, posts) {
    super(name);
    this.posts = posts;
  }
  getName() {
    const rename = super.getName();
      console.log(rename, '리네임')
    if (rename === '') {
      return 'Unknwon';
    }
    return rename;
  }
}
const dd = new Child();
dd // Child {name: '시바브라더', posts: undefined}
const dd = new Child('', 'you are')
dd // Child {name: '시바브라더', posts: 'you are'}
dd.getName('') // '시바브라더'

3) instanceof

user instanceof User (object instanceof Class)
user 객체가 User 클래스의 인스턴스인지 아닌지를 구별한다. -> return boolean

profile
delilah's journey

0개의 댓글