>  기사  >  웹 프론트엔드  >  Javascript의 setTimeout 콜백에서 \"this\" 키워드를 올바르게 사용하는 방법은 무엇입니까?

Javascript의 setTimeout 콜백에서 \"this\" 키워드를 올바르게 사용하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-10-24 10:37:30393검색

How to Use

JavaScript의 setTimeout 및 "this"

JavaScript에서 setTimeout 함수를 사용할 때 this 키워드가 콜백 함수. 경우에 따라 시간 초과 지연 후 참조된 메서드가 정의되지 않았다는 오류가 발생할 수 있습니다.

다음 코드를 고려하세요.

<code class="javascript">test.prototype.method = function() {
    // method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method, 5000);
};

test.prototype.method2 = function(name) {
    for (var i = 0; i < document.images.length; i++) {
        if (document.images[i].id.indexOf(name) > 1) {
            return document.images[i];
        }
    }
};</code>

이 예에서는 메서드 함수가 호출됩니다. 시간 제한은 5000밀리초입니다. 그러나 시간 초과 후에는 콜백 함수 내에서 method2 함수에 더 이상 액세스할 수 없습니다. 이는 this 키워드가 테스트 프로토타입의 인스턴스가 아닌 전역 개체를 참조하기 때문입니다.

이 문제를 해결하려면 setTimeout을 호출하기 전에 this 키워드를 콜백 함수에 바인딩할 수 있습니다. 이는 .bind(this) 메소드를 사용하여 달성할 수 있습니다.

<code class="javascript">test.prototype.method = function() {
    // method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method.bind(this), 5000);
};</code>

this 키워드를 콜백 함수에 바인딩하면 제한 시간이 경과한 후에도 method2 함수에 계속 액세스할 수 있습니다.

위 내용은 Javascript의 setTimeout 콜백에서 \"this\" 키워드를 올바르게 사용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.