Skip to content

Instantly share code, notes, and snippets.

@amorfati0310
Last active May 24, 2018 11:29
Show Gist options
  • Save amorfati0310/511c2fde3b4403bb1a9e391c2fa81292 to your computer and use it in GitHub Desktop.
Save amorfati0310/511c2fde3b4403bb1a9e391c2fa81292 to your computer and use it in GitHub Desktop.
this
//2초뒤에 'codesquad'가 출력되도록 코드를수정하세요. (출력은 printMyname을 통해서 할 수 있음)
//(a,b객체를 직접 부를 수 없음. bind,call 등을 사용해야 함)
let a = {
run() {
setTimeout( ()=> {
const name = this.getName();
printMyname(name)
},10);
}
}
let b = {
start(printMyname) {
setTimeout(function(){
a.run.call(b)
},10);
},
getName() {
return 'codesquad'
}
}
let printMyname = (name) => console.log(name);
b.start(printMyname);
@amorfati0310
Copy link
Author

설명

  1. b.start 메소드에 스트링을 받아 출력해주는 printMyname함수를 매개변수로 넘겨주고 실행시킵니다.
  2. setTimeout안에 함수가 비동기로 실행되고 후에 a.run()이 실행됩니다. a.run에서 getName이라는 b에 메소드가 필요하므로
    a.run()이 불릴떄 .call(b)로 b를 호출해줍니다
    내부에서 printMyname을 closer로 접근 가능하므로 이를 이용해서 내부에서 codeSquad를 출력해줍니다.
    혹은 printMynmae(a.run.call(b))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment