** 출처 http://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind
Use
.bind()
when you want that function to later be called with a certain context, useful in events.Use
.call()
or.apply()
when you want to invoke the funciton immediately, and modify the context.
.bind() 함수는 파라미터를 맵핑해서 함수를 리턴하고, 이렇게 재정의된 함수를 이벤트나 콜백 처리용으로 사용한다.
.call()과 .apply() 함수는 파라미터를 맵핑해서 즉시 실행하는 함수로 동작은 완전히 일치하지만, .apply() 함수의 경우 arguments로 파라미터가 리스트로 전달된다는 차이점만 있다.
call attaches this into function and executes the function immediately:
var person = { name: "James Smith", hello: function(thing) { console.log(this.name + " says hello " + thing); } } person.hello.call(person, "world"); // output: "James Smith says hello world"
bind attaches this into function and it needs to be invoked separately like this:
var person = { name: "James Smith", hello: function(thing) { console.log(this.name + " says hello " + thing); } } var helloFunc = person.hello.bind(person); helloFunc("world"); // output: "James Smith says hello world"
or like this:
// ... var helloFunc = person.hello.bind(person, "world"); helloFunc(); // output: "James Smith says hello world"
apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:
function personContainer() { var person = { name: "James Smith", hello: function() { console.log(this.name + " says hello " + arguments[1]); } } person.hello.apply(person, arguments); } // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars" personContainer("world", "mars");
또 다른 예제:
function multiplication(a,b){ console.log(a*b); } // .bind() 사용 var getSixAlways = multiplication.bind(this,3,2); getSixAlways(); // ==> 6 // .call() 사용 magicMultiplication.call(this,3,2); // ==> 6 // .apply() 사용 magicMultiplication.apply(this,[5,2]); // ==> 10
콜백함수 사용시 .bind() 함수를 쓰면 좋다.
> var fn = function( callback ){ ... console.log("defined by fn"); ... if( typeof callback !== 'undefined' ) callback(); ... }; > var multiple = function( a, b){ ... var result = a * b; ... console.log("multiple: "+a+" * "+b+" = "+result); ... }; > var m1 = multiple.bind(this, 2, 3); > m1(); multiple: 2 * 3 = 6 > fn( m1 ); defined by fn multiple: 2 * 3 = 6 > var m2 = multiple.bind(this, 5, 2); > fn( m2 ); defined by fn multiple: 5 * 2 = 10