apply ํ•จ์ˆ˜

apply() ํ•จ์ˆ˜๋Š” ๋‘ ๊ฐœ์˜ ์ธ์ž๋ฅผ ๋ฐ›๋Š”๋‹ค. ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

func.apply(thisArg, [argsArray]);
  • thisArg : ํ•จ์ˆ˜์— ์ง€์ •๋  this
  • argsArray : ํ•จ์ˆ˜์— ์ธ์ž๋กœ ์ „๋‹ฌ๋  ์œ ์‚ฌ๋ฐฐ์—ด๊ฐ์ฒด

์ด๋•Œ ์œ ์‚ฌ๋ฐฐ์—ด๊ฐ์ฒด๋ž€ ๋ฐฐ์—ด๊ณผ ๊ฐ™์ด index๋กœ ์ ‘๊ทผ ๊ฐ€๋Šฅํ•˜๋ฉฐ, length ํ”„๋กœํผํ‹ฐ๊ฐ€ ์žˆ๋Š” ๊ฐ์ฒด๋ฅผ ๋งํ•œ๋‹ค.


thisArg

์ฒซ๋ฒˆ์งธ ์ธ์ž๋Š” thisArg ํ˜ธ์ถœ๋  ํ•จ์ˆ˜์—๊ฒŒ ์ง€์ •๋  this์˜ ๊ฐ’์ด๋‹ค. apply()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ด๋ฏธ ์กด์žฌํ•˜๋Š” ํ•จ์ˆ˜func๋ฅผ thisArg ์˜ ๋ฉ”์„œ๋“œ์ฒ˜๋Ÿผ ํ˜ธ์ถœํ•ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

์•„๋ž˜์˜ ์ฝ”๋“œ์—์„œ๋Š” String ๊ฐ์ฒด์˜ ํ”„๋กœํ† ํƒ€์ž… ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ๋ฌธ์ž์—ด ์ž๋ฃŒํ˜•์—์„œ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•ด์•ผ ํ•˜์ง€๋งŒ, apply()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋‹ค๋ฅธ ์ž๋ฃŒํ˜•์—์„œ๋„ ์ž์œ ๋กญ๊ฒŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.

String.prototype.using = function(){
    console.log("์ด ํ•จ์ˆ˜๋ฅผ " + this.__proto__.constructor.name + " ์ž๋ฃŒํ˜• ์—์„œ ์‚ฌ์šฉํ•˜์˜€๋‹ค.");
    console.log(arguments);
    return;
}

console.log(String.prototype.using.apply(true, [ 1, 2, 3 ]));
// ์ด ํ•จ์ˆ˜๋ฅผ Boolean ์ž๋ฃŒํ˜• ์—์„œ ์‚ฌ์šฉํ•˜์˜€๋‹ค. ๋ฅผ ์ถœ๋ ฅ
// Arguments(3) [1, 2, 3, callee: (...), Symbol(Symbol.iterator): ฦ’]

argsArray

๋‘๋ฒˆ์งธ ์ธ์ž argsArray๋Š” ์œ ์‚ฌ๋ฐฐ์—ด๊ฐ์ฒด๋ฅผ ๋ฐ›๋Š”๋‹ค. ์ด๋•Œ ์ฃผ์˜ํ•ด์•ผํ•  ์ ์€ ๋‘๋ฒˆ์งธ ์ธ์ž๋ฅผ ์˜๋„๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ๊ฐ์ฒด์ž๋ฃŒํ˜•์ด๋ฉด์„œ(typeof ์—์„œ object๊ฐ€ ์ถœ๋ ฅ๋˜๋Š”) length ํ”„๋กœํผํ‹ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๊ณ  ๋งˆ์น˜ ๋ฐฐ์—ด์ฒ˜๋Ÿผ ์‚ฌ์šฉํ• ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค๋Š” ์ ์ด๋‹ค.


  • ๋ฌธ์ž์—ด์˜ ๊ฒฝ์šฐ

    // ๊ธฐ๋ณธํ˜• ๋ฌธ์ž์—ด
    console.log(String.prototype.using.apply(null, "string"));
    // Uncaught TypeError: CreateListFromArrayLike called on non-object
    
    // ์ƒ์„ฑ์ž๋กœ ๋งŒ๋“  ๋ฌธ์ž์—ด
    var string = new String("string");
    console.log(String.prototype.using.apply(null, string));
    // Arguments(6) ["s", "t", "r", "i", "n", "g", callee: (...), Symbol(Symbol.iterator): ฦ’]
  • ๊ฐ์ฒด์˜ ๊ฒฝ์šฐ

    // length ํ”„๋กœํผํ‹ฐ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ
    obj = {0:0, 1:1, 2:2}
    console.log(String.prototype.using.apply(true, obj));
    // Arguments [callee: (...), Symbol(Symbol.iterator): ฦ’]
    
    // length ํ”„๋กœํผํ‹ฐ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ
    obj = {0:0, 1:1, 2:2, length:3}
    console.log(String.prototype.using.apply(true, obj));
    // Arguments(3) ["0", "1", "2", callee: (...), Symbol(Symbol.iterator): ฦ’]
    
    // length ํ”„๋กœํผํ‹ฐ๊ฐ€ ์žˆ์œผ๋‚˜ key๊ฐ€ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ๊ฒฝ์šฐ
    obj = {"์˜":0, "์ผ":1, "์ด":2, length:3}
    console.log(String.prototype.using.apply(true, b));
    // Arguments(3) [undefined, undefined, undefined, callee: (...), Symbol(Symbol.iterator): ฦ’]

์ฐธ๊ณ