JavaScript
[JavaScript] call, apply
힘없는염소
2015. 10. 15. 17:33
var name = "window";function sayNameForAll(label) {console.log(label + ":" + this.name);}var person1 = {name: "사람1"};var person2 = {name: "사람2"};// Function.apply() 또는 Function.call()을 사용하면 Fucntion 자신을 나타내는 this를 변경할 수 있다.// 첫 번째 인수는 함수를 실행할 때 this로서 사용될 Object 이다. 두 번째 인수부터는 매개변수// fun.call(thisArg[, arg1[, arg2[, ...]]])// fun.apply(thisArg, [argsArray])sayNameForAll.call(this, "global"); // "global:window" 출력sayNameForAll.call(person1, "person1"); // "person1:사람1" 출력sayNameForAll.call(person2, "person2"); // "person2:사람2" 출력
반응형