이전 시리즈 글 : 코드 최적화 - 1. this.~ 문의 사용 보러가기 

이전 시리즈 글 : 코드 최적화 - 2. 유효성 검사 보러가기

이전 시리즈 글 : 코드 최적화 - 3. for문과 forEach문

 


 

개요

  • 개요는 시리즈 1과 동일 
  • 이하에서는 간결한 코드 작성하는 몇 가지 팁 정리함

 


 

1. 삼항 연산자 ? :  

  • 조건에 따라 값을 선택하는 자바스크립트의 표현 식
// 기본 구조 
(condition) ? trueExpression : falseExpression;
  • 예시 코드 : 프로젝트에 적용
this._result.forEach( (res) => {
  ctx.fillStyle = res.handedness === "Left" ? "Red" : "Blue";  // 조건식 쓸 때 왼쪽처럼 등호 2번 사용 가능!
  ctx.strokeStyle = "White";
  ctx.lineWidth = 2;
  res.keypoints.forEach(keypoint => {
      this._drawKeypoint(ctx, keypoint);
  });
  Object.keys(FINGER_INDICES).forEach(finger => {
      const points = FINGER_INDICES[finger].map(idx => res.keypoints[idx]);
      this._drawPath(ctx, points, false);
  });
});

// 최솟값 찾기
const a = 5;
const b = 10;
const min = (a < b) ? a : b;
console.log(min); // 출력: 5

 


 

2. && 연산자 활용

  • 값이 존재할 때만 출력
  • 예시 코드
const message = "안녕하세요!";
message && console.log(message);

     


 

3. filter 문 활용

  • 배열에서 특정 조건을 만족하는 값만 필터링
  • filter 문은 배열에서만 사용 가능
  • 예시 코드
const numbers = [1, 2, 3, 4, 5];
// 홀수만 필터링
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(oddNumbers); // 출력: [1, 3, 5]

문제 인식

  • 이번 프로젝트 (hand-pose-detection, face-landmarks-detection, pose-detection) 기능 구현은 완료했음. 
  • 그러나 기능 구현이 된 코드가 매!우! 더러웠음. 난도질 수준... 따라서 본격적으로 코드 최적화를 고민하기 시작함
  • 이하 내용 및 시리즈로 작성할 내용들은 ①기존 회사 코드 ②각종 공식 문서 ③GPT 와 함께 최적화한 코드 중에서, 3번 이상 자주 사용한 내용임
  • 이하 글 및 코드의 근본적인 출처는 https://ko.javascript.info/object-methods#ref-272
 

메서드와 this

 

ko.javascript.info

 


 

1. 의미

  • 현재 객체. 따라서 기본적으로 메서드 내부에서 this 키워드를 사용하면 객체에 접근 가능
let user = {
  name: "John",
  age: 30,
  sayHi() {
    // 'this'는 '현재 객체'를 나타냅니다.
    alert(this.name);
  }
};
user.sayHi(); // John
  • 자바스크립트에서는 모든 함수에 this 사용 가능 (다른 프로그래밍 언어와 상이)
  • this 값은 런타임에 따라 결정됨. = 컨텍스트에 따라 달라짐. = 동일한 함수라도 다른 객체에서 호출했다면 this가 참조하는 값이 달라짐
let user = { name: "John" };
let admin = { name: "Admin" };

function sayHi() {
  alert( this.name );
}

// 별개의 객체에서 동일한 함수를 사용함
user.f = sayHi;
admin.f = sayHi;

// 'this'는 '점(.) 앞의' 객체를 참조하기 때문에
// this 값이 달라짐
user.f(); // John  (this == user)
admin.f(); // Admin  (this == admin)

admin['f'](); // Admin (점과 대괄호는 동일하게 동작함)

 


 

2. 프로젝트에 적용

  • _함수명을 호출할 때, this._함수명() 사용
_createDetector() {
  const model = SupportedModels.MediaPipeHands;
  const detector = createDetector(model, {
      runtime: "tfjs",
      modelType: "lite",
      maxHands: 2, // or 2~10.
      flipHorizontal: false,
      staticImageMode: false,
      detectorModelUrl:
          "/static/tensorflow-models/tfjs-model_handpose_3d_detector_lite_1/model.json",
      landmarkModelUrl:
          "/static/tensorflow-models/tfjs-model_handpose_3d_landmark_lite_1/model.json",
  });
  return detector;
}

// this._함수명 으로 호출 
detect(imageData) {
    if (!this._detector) {
        this._createDetector().then(detector => {
            this._detector = detector;
            console.log("model loading success!, detector: ", this._detector);
        })
    }
//... 중략
}
  • 생성자 함수에서 메서드, 프로퍼티 초기화할 때 사용 : 즉, 메서드는 객체로 this를 참조
class Animal {
  constructor(name) {
    this.speed = 0;
    this.name = name;
  }
  run(speed) {
    this.speed = speed;
    alert(`${this.name} 은/는 속도 ${this.speed}로 달립니다.`);
  }
  stop() {
    this.speed = 0;
    alert(`${this.name} 이/가 멈췄습니다.`);
  }
}

let animal = new Animal("동물");

 

+ Recent posts