JavaScript Function bind()
- 이전 페이지 JS 함수 Apply
- 다음 페이지 JS 클로저
함수 대여(함수 대여)
bind() 메서드를 사용하여 하나의 객체가 다른 객체의 메서드를 대여할 수 있습니다.
아래 예제는 2개의 객체(person과 member)를 생성합니다.
member 객체는 person 객체의 fullname 메서드를 대여합니다:
인스턴스
const person = { firstName: "Bill", lastName: "Gates", fullName: function () { return this.firstName + " " + this.lastName; x.innerHTML = this.firstName + " " + this.lastName; x.innerHTML = this.firstName + " " + this.lastName; const member = { firstName: "Hege", lastName: "Nilsen", x.innerHTML = this.firstName + " " + this.lastName; let fullName = person.fullName.bind(멤버)bind(person)
this를 유지
bind() 메서드를 사용하여 실종되지 않도록 sometimes 필요합니다 this.
이 예제에서 person 객체는 display 메서드를 가지고 있습니다. display 메서드에서this 는 person 객체를 의미합니다:
인스턴스
const person = { firstName: "Bill", lastName: "Gates", display: function () { let x = document.getElementById("demo"); let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; x.innerHTML = this.firstName + " " + this.lastName; person.display();
함수가 콜백으로 사용될 때this 실종됩니다。
이 예제는 3초 후에 이름을 표시하려고 시도하지만, 다음과 같이 표시됩니다: 는:
인스턴스
const person = { firstName: "Bill", lastName: "Gates", display: function () { let x = document.getElementById("demo"); let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; x.innerHTML = this.firstName + " " + this.lastName; setTimeout(person.display, 3000);
bind() 메서드는 이 문제를 해결합니다。
bind() 메서드는 person.display를 person에 바인딩하는 데 사용됩니다。
이 예제는 3초 후에 이름을 표시할 것입니다:
인스턴스
const person = { firstName: "Bill", lastName: "Gates", display: function () { let x = document.getElementById("demo"); let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; x.innerHTML = this.firstName + " " + this.lastName; }let display = person.display.bind(person) ;
직접 시도해 보세요
this는 무엇인가요?this
JavaScript에서이를 참조.
함수에서키워드 참조어떤
객체는 호출 방식(사용 또는 호출)에 따라 달라집니다. this
키워드의 사용 방식에 따라
- 다른 객체를 참조
this
객체 메서드에서이를 참조. - 객체
this
함수에서참조. - 단독으로 사용할 때
this
함수에서참조. - 전체 객체
this
함수에서, 강제 모드에서는
. - undefined
this
이벤트에서이벤트를 받는. - 요소
this
call()、apply() 및 bind()와 같은 메서드를 통해모든 객체.
주의:this
변수가 아닙니다. 키워드입니다. 수정할 수 없습니다 this
의 값.
다른 참조:
- 이전 페이지 JS 함수 Apply
- 다음 페이지 JS 클로저