WJ
this에 대한 이해하기 본문
다른 언어들에서 this는 클래스로부터 생성되는 인스턴스(어떤 집합에 속하는 개별적인 요소) 중 현재 객체를 의미한다고 합니다. 하지만 자바스크립트에서 this는 함수의 현재 실행 문맥(Execution Context)을 나타내며, 자바스크립트에는 4가지의 함수 실행 타입이 있기 때문에 각각의 실행 타입에 따라 this가 변하게 됩니다.
함수 실행 : alert('Hello World!');
메소스 실행 : console.log('Hello World!');
생성자 실행 : new RegExp('\d');
간접 실행 : alert.call(undefined, 'Hello World!');
"use stirct"
function f1(){return this;}
if(f1() === window){console.log("true입니다.");}else{console.log("false입니다.");}
//false입니다.
비엄격모드에서의 결과
엄격모드에서의 결과
https://stackoverflow.com/questions/9822561/why-is-this-in-an-anonymous-function-undefined-when-using-strict
아래 처럼 this에 원하는 객체를 지정하고 내용을 추가하여 호출하여 사용할 수 있습니다. 또한 함수호출 없이 바로 함수가 실행되어
woongjin says helloworld 라는 결과가 출력 되었습니다.
var person = {
hello : function(thing){
console.log(this.name + " says hello" + thing);
}
}
person.hello.apply({ name: "woongjin" }, ["world"]);
// 실행 결과 : woongjin says helloworld
call
call은 apply 와 같은 기능을 가지고 있습니다. 차이점을 call은 인자를 배열로 받지 않는다는 점입니다.
apply에서 처음 사용했던 코드처럼 ex.apply(null,[1,2,3]); 인자를 배열형식으로 사용한다면 apply 그렇지 않다면
call을 사용해 ex.call(null,1,2,3); 처럼 입력하면 같은 결과를 출력 하게됩니다.
hello : function(thing){
console.log(this.name + " says hello" + thing);
}
}
var hellowFunc = person.hello.apply({ name: "woongjin" }, "world");
helloFunc();
// 실행 결과 : woongjin says helloworld
참조
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this
http://poiemaweb.com/js-this
https://hyunseob.github.io/2016/03/10/javascript-this/
http://blog.jeonghwan.net/2017/10/22/js-context-binding.html
http://webframeworks.kr/tutorials/translate/explanation-of-this-in-javascript-1/
'Javascript' 카테고리의 다른 글
실행 컨텍스트 (EXECUTION CONTEXT) 이해하기 (0) | 2017.12.17 |
---|---|
프로토타입 및 프로토타입 체인에 대해 이해하기 (0) | 2017.12.03 |
클로져에 대해 이해하기 (0) | 2017.12.03 |
함수 선언에 따른 차이 이해하기 (0) | 2017.12.03 |
SCOPE(변수 범위) 이해하기 (0) | 2017.12.03 |