What's this?

2877 단어
What's this?
실행 기 바 인 딩 특성 상 자 바스 크 립 트 의 this 의 미 는 매우 많 습 니 다. 전체 대상, 현재 대상 또는 임 의 대상 일 수 있 습 니 다. 이것 은 함수 호출 방식 에 달 려 있 습 니 다.
함수 사용 장소 에 따라 this 의 값 이 달라 집 니 다.그러나 하나의 총체적인 원칙 이 있다. 그것 이 바로 this 가 가리 키 는 것 은 함 수 를 호출 하 는 그 대상 이다
함수 호출
함수 가 직접 호출 될 때 this 는 전역 대상 에 연 결 됩 니 다.브 라 우 저 에서 window 는 이 전역 대상 입 니 다.
console.log(this);  //Window

function fn1(){
    function fn2(){
      console.log(this);
    }
}

fn1();  //Window


플러그 인 호출
함수 가 포 함 된 내부 함수 this 는 부모 함수 가 아니 라 전역 변수 입 니 다.
console.log(this);  //Window

function fn1(){
    function fn2(){
      console.log(this);
    }
    fn2()
}

fn1();  //Window

setTimeout、setInterval
문서 가 져 오기:
document.addEventListener('click', function(e){
  console.log(this);
  var _this = this;
  setTimeout(function(){
      console.log(_this);
  }, 200);
}, false);

대상 방법 으로 호출
JavaScript 에서 함수 도 대상 이기 때문에 함 수 는 하나의 대상 의 속성 으로 할 수 있 습 니 다. 이때 이 함 수 는 이 대상 의 방법 이 라 고 불 립 니 다. 이러한 호출 방식 을 사용 할 때 this 는 자 연 스 럽 게 이 대상 에 연결 되 어 있 습 니 다.
var obj1 = {
    name: 'Byron',
    fn : function(){
        console.log(this);
    }
};

obj1.fn();//Object {name: "Byron", fn: function}

var fn2 = obj1.fn;

fn2(); //window,   window.fn2()

Function.prototype.bind
bid, 새로운 함 수 를 되 돌려 주 고 함수 내부 의 this 를 들 어 오 는 첫 번 째 매개 변수 로 합 니 다.
document.addEventListener('click', function(e){
  console.log(this);
  setTimeout(function(){
      console.log(this);
  }.bind(this), 200);
}, false);

call 과 apply 를 사용 하여 this 설정 하기
    var value = 100;
    var obj = {
        value: 200
    }

    function fn(a,b){
        console.log(this.value + a + b)
    }

    fn(3,4) //107

    fn.call(obj,3,4)    //207
    fn.apply(obj, [3,4])  //207

배열 의 최대 값 을 얻다.
var arr = [1,3,12,3]
console.log( Math.max.apply(null, arr) )  //12

맞 춤 문자열
    function joinStr(){
        //1.
        console.log( Array.prototype.join.call(arguments, '-'))
        //2.
        var join = Array.prototype.join.bind(arguments);
        console.log(join('-'))
    }

    joinStr('a','b','c')

세 가지 변수
  • 인 스 턴 스 변수: (this) 클래스 의 인 스 턴 스 만 접근 할 수 있 는 변수
  • 정적 변수: (속성) 직접 유형 대상 이 접근 할 수 있 는 변수
  • 사유 변수: (국부 변수) 현재 작용 역 내 유효한 변수
  • function ClassA(){
        var a = 1; //    ,          
        this.b = 2; //    ,        
    }
    
    ClassA.c = 3; //     ,     ,    
    
    console.log(a); // error
    console.log(ClassA.b) // undefined
    console.log(ClassA.c) //3
    
    var classa = new ClassA();
    console.log(classa.a);//undefined
    console.log(classa.b);// 2
    console.log(classa.c);//undefined
    

    좋은 웹페이지 즐겨찾기