JS를 처음 사용하므로 참조를 바인딩하는 올바른 방법에 대한이 초보자 질문이 있습니다. 예를 들어 TypeScript에 다음 코드 줄이 있습니다.
this.socket.on('new_task').subscribe(this.newTask);
...
newTask(data) {
this.logEvent('new_task', data);
this.audio.playNewJob();
}
logEvent(event: string, data) {
console.log(this.TAG + event + ' triggered with received data: ' + JSON.stringify(data));
}
이걸 실행하면 다음을 얻을 수 있습니다 :
TypeError: this.logEvent is not a function
다음으로 변경하면 :
this.socket.on('new_task').subscribe((data) => this.newTask(data));
모든 것이 잘 작동하지만 JS 및 TS 기능을 사용하는 나쁜 방법처럼 보입니다. 이 경우 권장되는 방법은 무엇입니까?
- 답변 # 1
- 답변 # 2
문제는 "this"가 어떻게 바인딩되는지, 실행 시간에 완료되므로 logEvent 함수가 호출 될 때 해당 함수가없는 전역 객체를 나타냅니다. 두 번째 예제는 괜찮습니다.이 경우 화살표 함수가 정의 될 때 바인딩됩니다. 대안은 이것에 대한 참조를 저장하고 함수를 호출하는 것이지만 개인적으로는 화살표 함수 접근 방식을 선호합니다. 모든 사람들이 이것에 동의하지는 않지만 c #에서 함수를 화살표로 사용하는 데 익숙합니다. 차이점을 이해하고 더 쉽게 이해할 수있을뿐만 아니라 이에 대한 추론 방법을 이해한다고 생각합니다.
- 답변 # 3
method
대신속성으로이 문제에 직면했습니다. . 즉"속성 구문"으로 동일한 기능을 선언 할 수 있습니다. 여기서 속성은 함수 (newTask
) 아래는 방법,newTaskAsProperty
입니다 더 속성 -ish입니다)class MyClass { newTask(data) { this.logEvent('new_task', data); this.audio.playNewJob(); } newTaskAsProperty = (data) =>{ this.logEvent('new_task', data); this.audio.playNewJob(); } ...
흥미로운 것은 번역 된 결과 일 것입니다 :
var MyClass = (function () { function MyClass() { var _this = this; this.newTaskAsProperty = function (data) { _this.logEvent('new_task', data); _this.audio.playNewJob(); }; } MyClass.prototype.newTask = function (data) { this.logEvent('new_task', data); this.audio.playNewJob(); };
그래서 재산 접근 방식 (
newTaskAsProperty = (data) =>{}
)는 프로토 타입이 아닌 생성자에서 인스턴스에 적용됩니다. 그래서 대리인으로 사용하는 것이 예상대로 작동하는 이유// not working // this.socket.on('new_task').subscribe(this.newTask); // working this.socket.on('new_task').subscribe(this.newTaskAsProperty);
유일한 단점은방법이 아님입니다. 즉, 재정의 할 수 없습니다.
해결책으로, 우리는 간단히 그 안에 실제 메소드를 호출 할 수 있습니다-필요한 경우 그 메소드는
this
올바르게 설정되어 재정의 될 수 있습니다 ...
관련 자료
- TypeError : (0, _analytics.analytics) is not a function) Google Analytics react native
- javascript - wswrite = (resultjoin ( ',') + '\ n');&&typeerror - resultjoin은 함수가 아닙니다…이 유형 오류를 해결하는 방법
- reactjs - reactjs - typeerror : collegemap은 함수가 아닙니다
- vue.js - 잡히지 않은 typeerror - vueuse는 함수가 아닙니다
- javascript - typeerror - fnbind는 discordjs 길드원 업데이트 이벤트 기능이 아닙니다
- javascript - 잡히지 않은 typeerror - datareduce는 함수가 아닙니다 :d3js v5
- javascript - typeerror - resressent는 함수가 아닙니다
- typescript - jest typeerror - configserviceget은 함수가 아닙니다
- javascript - 양식 함수 유효성 검사 문제 (uncaught typeerror - cannot read property 'value'of null)
- node.js - 유형 오류 [err_invalid_callback] - 콜백은 함수 여야합니다 nodejs에서 undefined 수신
- javascript - "typeerror - typesmap은 함수가 아닙니다" reactjs
- microsoft excel - 결과 문자열이 아닌 함수에서 셀 참조 대체
- javascript - 처리되지 않은 거부 (typeerror) - storageput이 함수가 아닙니다
- python - "typeerror - 제네릭 유형에 대한 매개 변수는 유형이어야합니다 0을 얻었습니다" 내 기능에서
- javascript - typeerror - listpush는 localstorage로 푸시 할 때 함수가 아닙니다
- javascript - typeerror - elementsetattribute가 함수가 아닙니다 (react native/threejs)
- javascript - typeerror - funcapply는 함수가 아닙니다
- javascript - 유형 오류 : require (…) .listen은 함수가 아닙니다.
- javascript - 반응 - "typeerror : undefined는 함수가 아닙니다 ( '… formfieldsmap…'근처)"
- node.js - typeerror - sequelizeimport는 함수가 아닙니다
- Javascript /typescript에서 문자열 단어를 어떻게 굵게 표시합니까?
- javascript : TypeScript의 React 라우터 액세스 매개 변수
- javascript : toBe ()가 문자열 비교에 실패했습니다.
- javascript : 'Date []'유형의 인수를 수정하는 방법은 react에서 '(prevState : undefined) 유형의 매개 변수에 할당 할 수 없습니다.
- javascript : Splice가 배열 요소가 동일 할 때 마지막 요소 만 제거하는 이유
- javascript : React Typescript를 사용하여 react-leaflet-markerclusterer의 모든 클러스터 마커 표시
- javascript : require () 내에서 변수를 사용하는 방법은 무엇입니까?
- javascript : 본문 CSS를 변경하지 않고 보조보기가 열려있을 때 배경 페이지 스크롤을 비활성화하는 방법
- javascript : `children` 외에 소품이없는 React.PropsWithChildren?
- javascript : useState가 실행되기 전에 useState 후크의 초기 값 설정
로 변경