본문 바로가기

WEB/Javascript

bind, apply, call 정리

bind 함수

함수가 실행될때 함수를 특정 객체의 스코프 체인에 묶어버리는 기능이다.

Function.prototype.bind = function(scope) {

var _function = this;

return function {

return _function.apply(scope, arguments);

}

}

[참고]

http://sicheol.tistory.com/9#

패턴을 사용하거나 프레임웍 환경에서라면 좀더 직관적인 코딩을 위해 bind메소드가 필요


  1. var Controller = function(){}  
  2. Controller.prototype = {  
  3.     showMessage: function(){console.log('binding is fantastic');}  
  4. };  
  5. var controller = new Controller();  
  6. var btn = document.getElementById('btn');  
  7. btn.onclick = function(){this.showMessage();}.bind(controller);  




apply, call 함수

실행할 함수.apply(환경?객체?, 인자...);

실행 함수 내에서 this는 인자로 넘겨준 객체 이다.

그냥 실행하면 this는 window

* apply와 call은 인자 넘기는 형식만 다르다. apply는 배열로, call 은 각각 인자로 넘거줌.


var o = { x: 15 };
 
function f(message1, message2)
{
    alert(message1 + (this.x * this.x) + message2);
}
 
function g(object, func)
{          
    // arguments[0] == object
    // arguments[1] == func
     
    

    var args = []; // empty array
    // copy all other arguments we want to "pass through"
    for(var i = 2; i < arguments.length; i++)
    {
        args.push(arguments[i]);
    }
 
    func.apply(object, args);
}
 
g(o, f, "The value of x squared = ", ". Wow!");
// 호출한 함수의 파라미터가 넘겨준 인자 갯수와 맞지 않아도, arguments 배열에 모두 들어 있다 !!



[참고]

http://opentutorials.org/module/532/6550

o1 = {val1:1, val2:2, val3:3}
o2 = {v1:10, v2:50, v3:100, v4:25}
function sum(){
var _sum = 0;
for(name in this){
_sum += this[name];
}
return _sum;
}
alert(sum.apply(o1)) // 6
alert(sum.apply(o2)) // 185

다른 형태의 객체가 어떤 fucntion을 호출 할수 있도록 apply를 사용한다. 

sum.apply(null);  == sum();

sum.apply(객체); =  객체.sum() 이거와 비슷하나. sum은 객체의 변수가 아니다.


o1.sum = sum;
alert(o1.sum());
delete o1.sum();

apply 시 위와 같은 처리가 이루워 진다고 생각하면 된다.

전역 객체 이지만, 어떤 객체의 소유한 객체 처럼 실행 되도록 하는 기능이다.

'WEB > Javascript' 카테고리의 다른 글

클로저  (0) 2014.08.08
프로퍼티 속성  (0) 2014.07.15
Getter와 Setter 프로퍼티  (0) 2014.07.14