에 대해 이야기하겠습니다.
호출, 적용, 바인딩은 모두 '이'가 가리키는 대상을 변경하는 메서드입니다.
사용할 때 어떤 것을 사용해야할지 모르겠으므로 인상을 깊게하기 위해 여기에서 정리하겠습니다.
call
- call() 함수는 여러 개의 인수를 받으며, 첫 번째 인수는 this가 가리키는 객체, 후속 인수는 호출 함수에 전달된 매개변수, 반환 값은 지정된 this 값과 매개변수로 함수를 호출한 결과입니다.
call(thisArg, arg1, arg2, /* , */ argN)
- 첫 번째 this Arg 매개변수가 생략되면 기본값은 정의되지 않음으로 설정되며, 비엄격 모드에서는 this 값이 globalThis ".
var animal = '
var sleepDuration = "6 8시간으로"
function greet() {
console.log(this.animal, "수면 시간은 일반적으로 ", this.sleepDuration, "사이");
}
const obj = {
animal: " ,
sleepDuration: "12 16시간으로",
};
greet.call(obj); // 고양이는 일반적으로 12~16시간 정도 수면을 취합니다.
greet.call(); // 개는 일반적으로 6시간에서 8시간 정도 수면을 취합니다.
### 인사말에서.call(obj)실행될 때 greet() 함수의 this는 객체를 가리킵니다.
### 객체에 greet이라는 속성을 추가하는 것과 같으며, 그 값은 greet 함수입니다.,obj.greet = greet
### greet.call(obj) 객체가 됩니다..greet()
- 손글씨 통화
Function.prototype.zyCall = function(thisArg,...args){
const fn = this
// fn을 사용할 때.zyCall(obj),this는 항상 그것을 호출한 객체를 가리킵니다.,this == fn
thisArg = (thisArg !== null && thisArg !==undefined) ? Object(thisArg) : window
thisArg.fn = fn
const res = thisArg.fn(...args)
delete thisArg.fn
return res
}
apply
이 함수는 호출()과 거의 동일하지만 호출()에서는 함수 인수가 목록으로 하나씩 전달되는 반면, 적용()에서는 함수가 호출될 때 사용할 인수를 지정하는 클래스 배열 객체에 결합되거나 함수에 인수를 제공할 필요가 없는 경우 null 또는 정의되지 않은 인수가 전달된다는 점을 제외하면 호출()과 거의 동일합니다.
손글씨 적용
Function.prototype.zyApply = function(thisArg,argArray){
const fn = this
// fn을 사용할 때.zyCall(obj),this는 항상 그것을 호출한 객체를 가리킵니다.,this == fn
thisArg = (thisArg !== null && thisArg !==undefined) ? Object(thisArg) : window
thisArg.fn = fn
const res = thisArg.fn(...argArray)
delete thisArg.fn
return res
}
bind
- bind() 메서드는 호출 시 원래 함수를 호출하고 this 키워드를 지정된 값으로 설정하는 새 함수를 생성하고, 새 함수가 호출될 때 전달된 인수 앞에 삽입되는 지정된 인수 집합을 전달합니다. (원래 함수를 호출할 때 매개변수 arg1, 새 함수를 호출할 때 arg2, 새 함수의 실제 매개변수는 arg1과 arg2 두 개입니다).
bind(thisArg, arg1, arg2, /* , */ argN)
// 최상위 수준 "이"”"글로벌 "이"에 바인딩합니다.”
var x = 9;
const module = {
x: 81,
getX() {
return this.x;
},
};
// "getX”"이"”매개변수는 '모듈'에 바인딩됩니다.”
console.log(module.getX()); // 81
const retrieveX = module.getX;
// "retrieveX”"이"”매개변수는 비엄격 모드에서 "전역 "이"에 바인딩됩니다.”
console.log(retrieveX()); // 9
// 새 함수 "boundGetX"를 만듭니다.”,"이"를 넣습니다.”매개변수는 '모듈'에 바인딩됩니다.”
const boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81
bind() 함수는 새 . 바인드 함수를 호출하면 일반적으로 이 함수가 래핑하는 함수, 즉 . 바인드 함수는 바인딩할 때 전달된 인수를 내부 상태로 미리 저장합니다. 대신 실제 호출 시 인수가 전달됩니다. 일반적으로
const boundFn = fn.bind(thisArg, arg1, arg2)const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)구성된 바인드 함수를 호출할 때의 효과는 동일하다고 생각할 수 있습니다.를 호출하여 바인딩된 함수를 추가로 바인딩할 수 있으며, 이 경우 또 다른 바인딩된 함수 boundFn2가 생성됩니다. 새로 바인딩된 this Arg 값은 boundFn2의 대상 함수가 boundFn이고 boundFn에 이미 바인딩된 값이 있기 때문에 무시됩니다. "이" 값을 이미 가지고 있기 때문입니다. boundFn2가 호출되면 boundFn을 호출하고, 이 함수는 차례로 fn을 호출합니다. fn이 받는 최종 인수는 순서대로 boundFn에 바인딩된 인수, boundFn2에 바인딩된 인수, boundFn2가 받는 인수입니다.
"use strict"; // `this` 가 래퍼 객체에 캡슐화됩니다.
function log(...args) {
console.log(this, ...args);
}
const boundLog = log.bind("this value", 1, 2);
const boundLog2 = boundLog.bind("new this value", 3, 4);
boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6
- 손글씨 바인딩
Function.proptype.zyBind = function (thisArg, ...argArray) {
//1.호출할 실제 함수 가져오기
const fn = this
//2. "이"에 바인딩합니다.
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
function proxyFn(...args) {
//3.함수를 호출할 this 인수에 넣습니다.
thisArg.fn = fn
//특수: 들어오는 두 개의 매개변수를 병합합니다.
const finalArgs = [...argArray, ...args]
const res = thisArg.fn(...finalArgs)
delete thisArg.fn
//4.결과 반환
return res
}
//호출할 함수 자체(이 경우 "이" 값이 추가된 함수)를 반환합니다.
return proxyFn
}





