Last active
July 11, 2017 05:34
-
-
Save ibare/398ceb9c612c4dcf162d92cbf155cbb6 to your computer and use it in GitHub Desktop.
javascript 실행 콘텍스트의 변화
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Foo() { | |
// this 는 new 연산자로 호출되었을 때를 전제한다 | |
// this 는 인스턴스 객체 | |
this.myname = 'Foo'; | |
this.displayName = function() { | |
// this 는 인스턴스 객체를 전제한다. | |
// 따라서 반드시 [인스턴스].displayName() 으로 호출되어야한다 | |
// 그렇게 하지 못할 경우 인스턴스 객체를 바인딩 시켜줘야야 this 가 인스턴스 객체를 가르킨다 | |
// ㄴ displayName.bind([인스턴스]) | |
console.log(this.myname); | |
}; | |
} | |
// 함수를 대신 호출해 주는 함수 | |
function call(fn) { | |
fn(); | |
} | |
var foo = new Foo(); | |
foo.displayName(); // this 는 foo 가 된다 | |
call(foo.displayName); // this 는 window 객체가 된다 | |
call(foo.displayName.bind(foo)); // this 는 바인딩된 foo(인스턴스) 객체가 된다 | |
setTimeout(foo.displayName, 100); // this 는 window 객체가 된다 | |
setTimeout(function() { | |
foo.displayName(); // this 는 foo 객체가 된다 | |
}, 200); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
아... 이제 논리가 완전히 이해되었습니다! 한번 들었을 때에는 몰랐어요... 감사합니다 ㅠㅠ