.bind(thisArg[, arg1[, arg2[,...]]])
bind()
์ ์ญํ ์ ์๋ก์ด ํจ์๋ฅผ ๋ง๋ ๋ค.
์ด ํจ์์ ์คํ ๋ฌธ๋งฅ์ .bind()
์ ์ฒซ๋ฒ์งธ ์ธ์๋ก ๋ฐ์๊ฒ ๋๋ค.
๋ฐ์ธ๋ฉํจ์๋ ๋ฏธ๋ฆฌ ์ ์ํด๋ this
๊ฐ์ผ๋ก ํจ์๋ฅผ ์์ฑํ ์ ์๊ธฐ ๋๋ฌธ์ ๋งค์ฐ ์ ์ฉํ๋ค.
.call(thisArg[,arg1[,arg2[,...]]])
call()
ํจ์๋ ์ฒซ๋ฒ์งธ ์ธ์๋ก ํจ์ ๋ด๋ถ์์ ์ฌ์ฉํ this
๋ก ๋ง๋ค์ด์ค๋ค
๋๋จธ์ง parameter ๋ ๋ฉ์๋์ ์ ๋ฌํ ์ธ์ ๋ชฉ๋ก์ด๋ค.
.apply(thisArg[,argsArray])
apply()
ํจ์๋ call()
ํจ์์ ๋์ผํ์ง๋ง ๋ฐฐ์ด๋ก ๋ฉ์๋์ ์ธ์๋ฅผ ์ ๋ฌํ๋ค๋๊ฒ์ด ์ฐจ์ด์ด๋ค.
call()
๊ณผ apply()
๋ ํน์ ๊ฐ์ฒด์ ๋ฉ์๋๋ฅผ ๋น๋ ค์ด๋ค๋ ๊ฐ๋
์ด๊ณ
bind()
ํจ์๋ ํจ์๋ฅผ ๋ฆฌํดํ๋ค. ์ด ํจ์๋ ์์ ๋งํ๋ฏ์ด ๋ฏธ๋ฆฌ ์ ์ํด๋ this
๋ฅผ ๊ฐ์ง ์๋ก์ด ํจ์์ด๋ค.
function multiply(number) {
'use strict';
return this * number;
}
// ๋ฌธ๋งฅ์ ์ง์ ํด์ ๋ฐ์ธ๋ฉ ํจ์๋ฅผ ์์ฑ
var double = multiply.bind(2);
// ๋ฐ์ธ๋ฉ ํจ์๋ฅผ ์คํ
console.log(double(3)); // => 6
console.log(double(10)); // => 20
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
๋ฅผ ๋ถ์ด์ง ์๊ณ ํธ์ถํ ๊ฒฝ์ฐ 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