웹/javascript
setTimeout 과 this
java개발자
2018. 5. 19. 01:02
function fn1(){ console.log("this is window: " + this); } var obj2 = { name : "obj2Name" , age : 21 , fn2 : function(){ console.log("this is obj2: " + this); } , fn3 : function(){ this.age = this.age + 2; console.log("this is 5 " + this); console.log("obj2.age 5==" + obj2.age); } , fn4 : function(){ // 정상 console.log("this is obj2: " + this); this.age = this.age + 1; console.log("obj2.age==" + obj2.age); // 22 // 원하는 대로 되지 않음. // setTimeout(function(){ // console.log("this is window2: " + this); // 여기서 this는 window 객체다. 왜???? -- this를 obj2로 할 수 없나? // this.age = this.age + 1; // console.log("obj2.age==" + obj2.age); // 변하지 않는다. // }, 1000); // 에러 // window.setTimeout.call(this, this.fn3, 1000); // --> 에러 : Uncaught TypeError: Illegal invocation // 정상 // setTimeout(function(){ // obj2.fn3(); // obj2를 직접 명시하는 것은 별로다... // }, 1000); // 에러 // var st = setTimeout.bind(this); // st(this.fn3, 1000); // --> 에러 : Uncaught TypeError: Illegal invocation // 정상 // var this2 = this; // this를 임시 보관. 불필요한 변수 생성-_-;; // setTimeout(function(){ // this2.fn3(); // }, 1000); // 비정상 // setTimeout(this.fn3, 1000); // 여기 this는 obj2이지만, fn3 함수 내의 this가 window 객체가 된다-_-; // 성공 // 출처: https://coderwall.com/p/65073w/using-this-in-scope-based-settimeout-setinterval // >> setTimeout에 this를 bind하는게 아니라, fn3에 bind하는 거구나... setTimeout(this.fn3.bind(this), 1000); // this 2개 모두 obj2 } } // this 표시 fn1(); obj2.fn2(); obj2.fn4(); // 외부에서 실행하면 정상 // setTimeout(function(){ // obj2.age = obj2.age + 1; // console.log("obj2.age==" + obj2.age); // 22가 된다.(정상) // }, 1000); // obj2.fn3(); // console.log("obj2.age==" + obj2.age); // 24가 된다.(정상)