자바 스크립트 익명 함수 끝에 ".call (this)"을 쓰는 이유는 무엇입니까?
이 질문에 이미 답변이 있습니다.
- 이 자체 호출 익명 함수 변형의 이유 5 답변
나는 다음과 같이 작성된 자바 스크립트를 본 적이있다 (데모에 있었고 실제 코드는 없지만 이것이 정상임을 암시했다).
(function() {
var a = 1;
this.sayA = function() {
alert(a);
}
}).call(this);
sayA();
변수 a
를 전역 적으로 사용할 수 없도록 익명 함수로 작성되었다고 가정합니다 .
요점이 무엇일까요 .call(this)
? 이 함수는 중첩되지 않았으므로 this
단지 창이었습니다. ()
마지막에 쓰는 것과 어떻게 다른 가요?
이 시도:
function Foo() {
(function () {
console.log(this);
// > Foo
}).call(this);
(function () {
console.log(this);
// > undefined in strict mode, or Window in non strict mode
})();
}
var bar = new Foo;
따라서 어떤 이유로 든 이것을 사용하는 경우 , 특히 사용자 정의 개체 유형의 인스턴스 를 만들 때 IIFE가의 멤버 함수 인 것처럼 작동 하도록 만드는 방법 Foo
입니다.
이 비디오 에 대한 John Resig의 이야기를 방금 보았을뿐만 아니라 이것에 대해 궁금했습니다 . Yoshi는 훌륭한 답변을 받았지만 이해하기 위해 콘솔 로그에서 약간 테스트해야했으며 그의 답변에 대한이 수정이 처음에는 나처럼 문제가 있었던 일부 사람들에게 도움이 될 것이라고 생각했습니다.
function Foo() {
this.foo = true;
(function () {
console.log("Foo = " + this.foo);
// Outputs undefined
}());
(function () {
console.log("Foo = " + this.foo);
// Outputs true
}).call(this);
(function () {
console.log(this);
// Outputs undefined in strict mode, or Window in non strict mode
// Anonymous functions usually default to the global scope
})();
}
var bar = new Foo;
.call (this)이 기본적으로 현재 컨텍스트를 익명 함수에 전달할 수있는 기능을 제공한다는 것을 보여 주면서 첫 번째와 두 번째 항목을 나란히 보는 것이 조금 더 이해가되었습니다.
질문에 감사 드리며 명확한 답변에 대해 Yoshi에게 감사드립니다!
Since this function was not nested,
this
was just the window. How does it differ from just writing()
at the end?
No - not in strict mode:
- If the function code is strict code, set the
ThisBinding
tothisArg
.- Else if
thisArg
isnull
orundefined
, set theThisBinding
to the global object.- …
In strict mode, the this
is just directly set to the given value, which is undefined
for a normal call. Therefore, .call(this)
is used to pass the global object explicitly in. You can try this in the console:
> (function() { "use strict"; console.log(this); })()
undefined
> (function() { "use strict"; console.log(this); }).call(this)
Window
It might not make a difference for sloppy code, but it's a good practise and future-compatible :-)
this
passed to the function sets the context of the execution, so inside your anonymous function this
refers to the window
.
You can than write this.alert('');
.
ReferenceURL : https://stackoverflow.com/questions/8035822/why-write-callthis-at-the-end-of-an-javascript-anonymous-function
'Development Tip' 카테고리의 다른 글
Visual Studio가 MSBuild에 전달하는 매개 변수는 무엇입니까? (0) | 2020.12.31 |
---|---|
Sun VM에서 할 수있는 Dalvik VM (Android의 VM)에서 할 수없는 것은 무엇입니까? (0) | 2020.12.31 |
Python 3 인터프리터에 JIT 기능이 있습니까? (0) | 2020.12.30 |
Express.js 응답 시간 초과 (0) | 2020.12.30 |
translate3d 대 번역 성능 (0) | 2020.12.30 |