Study/JavaScript(Clean code)

[JavaScript][clean-code] Shorthand Properties

갈푸라떼 2022. 6. 6. 01:46

* Shorthand Properties

- 내가 사용하는 문법이 무엇이고 어떤값의 축약인지 파악하자.

- css는 속성을 attribute라고도 부른다. javascript에서는 property라고 한다. 이것도 하나의 예시이다.

 

* css에서의 Shorthand Properties예시

background-color
background-image
background-repeat
background-position

/* 아래와 같이 축약가능 */
background : #000 url(...)
margin-top : 10px;
margin-right : 5px;
margin-bottom: 10px;
margin-left : 5px;

/* 아래와 같이 축약 가능 */
margin : 10px 5px 10px 5px;

 

* JavaScript의 Shorthand Properties

  • 리액트에서 리덕스를 사용할 경우
  • combineReducers를 사용해서 특정 Reducer들을 결합할 때 사용
  • 아래의 예시 문법을 통해 Shorthand Properties를 확인
const counterApp = combineReducers({
  counter,
  extra,
});

* JavaScript Shorthand Properties가 사용되지 않은 예시

const person = {
  firstName : 'poco',
  lastName : 'jang',
  getFullName: function() {
    return thi.firstName + ' ' + this.lastName;
  },
};

* Concise Method

  • 간결하게 method를 사용하는 방법
  • JavaScript의 메서드를 조금 더 보기 편하게 명시적으로 만들어 준다.
// before
getFullName: function() {
    return this.firstName + ' ' + this.lastName;
}

// after
getFullName() {
    return this.firstName + ' ' + this.lastName;
}

* Shorthand Properties & Concise Method 가 사용된 예시

const firstName = 'poco';
const lastName = 'jang';

const person = {
  firstName,
  lastName,
  getFullName() {
    return this.firstName + ' ' + this.lastName;
  },
};
  • 코드 속성들을 축약해서 표현 가능
  • key와 value가 동일한 형태 혹은 변수에 담은 형태로 표현 되었을때 간결하게 표현할 수 있는 모든것들이 문법에서 추가적으로 지원해주는 것이다.
  • ES2015+에서 등장한 모던자바스크립트의 문법의 한 예시이다.
  • 리팩토링 할 때 좀 더 일관성있게 할 수 있다.