작성
·
263
0
안녕하세요. 얼마 전 bind 타입 분석을 하다가 궁금점이 풀리지 않아 질문 내역을 보았습니다.
22년 9월 13일 제목: 13:50 파라미터 질문 (해결)
이란 글의 질문과 같이 bind 인자로 받는 this 가 이해를 할 수 없었습니다. 현영님께서 답변을 달아주신 것을 봤지만 이해가 되지 않더라고요 이게 가능한건가?.. 싶었습니다.
현재 타입스크립트버전 "typescript": "^5.1.6"
lib.es5.d.ts 에 보면 bind는 아래와 같이 정의 되어있는데요
interface CallableFunction extends Function {
bind<T>(this: T, thisArg: ThisParameterType<T>): OmitThisParameter<T>;
bind<T, A extends any[], B extends any[], R>(this: (this: T, ...args: [...A, ...B]) => R, thisArg: T, ...args: A): (...args: B) => R;
}
mdn에서 bind 메서드를 확인해보니
func.bind(thisArg[, arg1[, arg2[, ...]]])
이러한 구문을 갖고 있는 것을 확인했습니다.
인자의 수가 안맞고 this라는 것은 찾아볼 수 없었는데요. 그래서 ECMAScript bind를 찾아보니 함수가 다음과 같이 정의 되었다는 것을 알게되었습니다.
20.2.3.2 Function.prototype.bind ( thisArg, ...args )
This method performs the following steps when called:
1. Let Target be the this value.
2. If IsCallable(Target) is false, throw a TypeError exception.
3. Let F be ? BoundFunctionCreate(Target, thisArg, args).
4. Let L be 0.
5. Let targetHasLength be ? HasOwnProperty(Target, "length").
6. If targetHasLength is true, then
a. Let targetLen be ? Get(Target, "length").
b. If targetLen is a Number, then
i. If targetLen is +∞𝔽, then
1. Set L to +∞.
ii. Else if targetLen is -∞𝔽, then
1. Set L to 0.
iii. Else,
1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen).
2. Assert: targetLenAsInt is finite.
3. Let argCount be the number of elements in args.
4. Set L to max(targetLenAsInt - argCount, 0).
7. Perform SetFunctionLength(F, L).
8. Let targetName be ? Get(Target, "name").
9. If targetName is not a String, set targetName to the empty String.
10. Perform SetFunctionName(F, targetName, "bound").
11. Return F.
bind가 수행되면 bound 된 함수를 반환해주는데 그 과정에서 1번에서 target은 this 값으로 설정이 되고
3번에 BoundFunctionCreate (target, thisArg, ...args) 로 설정되어 this가 들어가는 것으로 확인했습니다. 이 과정을 거쳐 bound된 함수를 반환해주는데
타입스크립트에서 정의된 this, thisArg, ...args 가 위 내용에 대한 타입 정의가 아닐까 싶습니다.
이전 답변에 궁금증이 해소되지않아 찾아봤는데 시간나실때 확인부탁드립니다!
ECMA bind 위에 링크 걸어두었습니다. 항상 좋은 강의와 정보제공 감사드립니다.:)
답변 1
0
아뇨 저 내용과는 관련이 없습니다. this는 자신이 직접 타이핑하는 bind 함수의 this입니다.
타입스크립트는 함수에서 this를 직접 타이핑할 수 있습니다.