문제 인식
- 이번 프로젝트 (hand-pose-detection, face-landmarks-detection, pose-detection) 기능 구현은 완료했음.
- 그러나 기능 구현이 된 코드가 매!우! 더러웠음. 난도질 수준... 따라서 본격적으로 코드 최적화를 고민하기 시작함
- 이하 내용 및 시리즈로 작성할 내용들은 ①기존 회사 코드 ②각종 공식 문서 ③GPT 와 함께 최적화한 코드 중에서, 3번 이상 자주 사용한 내용임
- 이하 글 및 코드의 근본적인 출처는 https://ko.javascript.info/object-methods#ref-272
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("동물");
'Backend > Node.js' 카테고리의 다른 글
[Coding-Practice] 코드 최적화 - 3. for문과 forEach문 (0) | 2023.11.30 |
---|---|
[Coding-Practice] 코드 최적화 - 2. 유효성 검사 (0) | 2023.11.30 |
[Function] 프로젝트 내에서 함수 구분 (1) | 2023.11.30 |
[Class] 클래스 상속 (0) | 2023.11.30 |
[Setting] npm link 2 (0) | 2023.11.30 |