Javascrip에서call과 apply의 용도

1260 단어
  • this의 지향을 바꿉니다 var obj1 = {name:'세븐'} var obj2 = {name:'name'} 윈도우.name = 'window'; var getName = function(){ console.log(this.name); };
    getName() // output window
    getName.call(obj1) // output seven
    getName.call(obj2) // output name
    
  • Function.prototype.bind Function.prototype.bind=function(context) {varself=this;/save the origin function context return function() {//return new function return self.apply(context,arguments);/use context replace the new function this}
    var obj = {
      name:'name'
    }
    
    var func = function(){
      console.log(this.name);
    }.bind(obj);
    
    func(); // name
    
    최적화 버전의bind Function.prototype.bind=function() {var_this=this,context=[].shift.call(arguments),//들어오는 실행 환경args=[].slice.call(arguments);//처음 들어오는 인자
      return function(){
          return _this.apply(context,[].concat.call(args,[].slice.call(arguments)));
      }
    }
    
    var obj = {
      name:'name'
    }
    
    var func = function(a,b,c,d){
      console.log(this.name);
      console.log([a,b,c,d]);
    }.bind(obj,12,23);
    
    func(34,45);
    
  • 다른 객체의 방법을 빌려 사용합니다.prototype.slice.call(arguments) 예를 들어 이 가장 흔히 볼 수 있는 변환arguments를 수조로 하는 hack 쓰기 방법은 Array의 슬라이스 방법을 빌려 변환하는 것이다.
  • 좋은 웹페이지 즐겨찾기