Skip to content

Latest commit

ย 

History

History
81 lines (67 loc) ยท 2.48 KB

bind.md

File metadata and controls

81 lines (67 loc) ยท 2.48 KB

bind, call, apply

bind()

.bind(thisArg[, arg1[, arg2[,...]]])

bind() ์˜ ์—ญํ• ์€ ์ƒˆ๋กœ์šด ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ ๋‹ค.
์ด ํ•จ์ˆ˜์˜ ์‹คํ–‰ ๋ฌธ๋งฅ์€ .bind()์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž๋กœ ๋ฐ›์€๊ฒŒ ๋œ๋‹ค.
๋ฐ”์ธ๋”ฉํ•จ์ˆ˜๋Š” ๋ฏธ๋ฆฌ ์ •์˜ํ•ด๋‘” this ๊ฐ’์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋งค์šฐ ์œ ์šฉํ•˜๋‹ค.

call()

.call(thisArg[,arg1[,arg2[,...]]])

call() ํ•จ์ˆ˜๋Š” ์ฒซ๋ฒˆ์งธ ์ธ์ž๋กœ ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ ์‚ฌ์šฉํ•  this๋กœ ๋งŒ๋“ค์–ด์ค€๋‹ค
๋‚˜๋จธ์ง€ parameter ๋Š” ๋ฉ”์„œ๋“œ์— ์ „๋‹ฌํ•œ ์ธ์ž ๋ชฉ๋ก์ด๋‹ค.

apply()

.apply(thisArg[,argsArray])

apply() ํ•จ์ˆ˜๋Š” call() ํ•จ์ˆ˜์™€ ๋™์ผํ•˜์ง€๋งŒ ๋ฐฐ์—ด๋กœ ๋ฉ”์„œ๋“œ์— ์ธ์ž๋ฅผ ์ „๋‹ฌํ•œ๋‹ค๋Š”๊ฒƒ์ด ์ฐจ์ด์ด๋‹ค.

ํ—ท๊ฐˆ๋ฆฌ๋Š” ๋ถ€๋ถ„

call() ๊ณผ apply() ๋Š” ํŠน์ • ๊ฐ์ฒด์˜ ๋ฉ”์„œ๋“œ๋ฅผ ๋นŒ๋ ค์“ด๋‹ค๋Š” ๊ฐœ๋…์ด๊ณ 
bind() ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ์•ž์„œ ๋งํ–ˆ๋“ฏ์ด ๋ฏธ๋ฆฌ ์ •์˜ํ•ด๋‘” this๋ฅผ ๊ฐ€์ง„ ์ƒˆ๋กœ์šด ํ•จ์ˆ˜์ด๋‹ค.

bind()์˜ˆ์ œ

function multiply(number) {
    'use strict';
    return this * number;
}
// ๋ฌธ๋งฅ์„ ์ง€์ •ํ•ด์„œ ๋ฐ”์ธ๋”ฉ ํ•จ์ˆ˜๋ฅผ ์ƒ์„ฑ
var double = multiply.bind(2);

// ๋ฐ”์ธ๋”ฉ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰
console.log(double(3));  // => 6
console.log(double(10)); // => 20

call(), apply() ์˜ˆ์ œ

var num = 5;
var obj = {
    num: 50
};

function double(){
    return this.num * 2;
}

// this ๋Š” window
console.log(double());
console.log(double.call(this));
console.log(double.apply(this));

// this ๋Š” obj
console.log(double.call(obj));
console.log(double.apply(obj));

์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ฅผ new ๋ฅผ ๋ถ™์ด์ง€ ์•Š๊ณ  ํ˜ธ์ถœํ•  ๊ฒฝ์šฐ

์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ฅผ new ๋ฅผ ๋ถ™์ด์ง€ ์•Š๊ณ  ํ˜ธ์ถœํ• ๊ฒฝ์šฐ this๋Š” ์ „์—ญ๊ฐ์ฒด์— ๋ฐ”์ธ๋”ฉ๋œ๋‹ค. ์ด๋Ÿฐ ํ˜„์ƒ์„ ๋ง‰๊ธฐ์œ„ํ•ด ๋„๋ฆฌ ์‚ฌ์šฉ๋˜๋Š” ํŒจํ„ด์ด ์žˆ๋‹ค.

function Foo(arg){
  // ์ƒ์„ฑ๋œ this ๊ฐ€ A์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด
  // new ์—ฐ์‚ฐ์„ ํ†ตํ•ด ๋ฐ”์ธ๋”ฉ
  if(!(this instanceof A)){
    return new Foo(arg);
  }

  this.value = arg ? arg : 0;
}

์ฐธ๊ณ  ๋ฌธ์„œ

https://goo.gl/z1qxC9
http://codepitcher.tistory.com/4
http://itstory.tk/entry/JavaScript-4-%ED%95%A8%EC%88%98%EC%99%80-%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85-%EC%B2%B4%EC%9D%B4%EB%8B%9D-2-this%EB%9E%80