javascript 의 this 분석

4480 단어
this 에 대해 이해 가 잘 안 되 고 앞 뒤 도 기술 서 를 읽 었 습 니 다. 앞으로 관련 블 로 그 는 드디어 뭔 가 를 정리 하고 싶 습 니 다.
this 는 서로 다른 상하 문 환경 에서 서로 다른 대상 을 가리 키 며, 성명 환경 과 무관 하 며, 운행 환경 과 관계 가 있다
  • this 는 전역 대상 window (서버 에서 global 을 가리 키 는)
  • var name = 'jack'
    function sayName () {
        console.log(this.name)
    }
    sayName() // jack
    
  • this 는 현재 호출 대상
  • 을 가리킨다.
    //      ,         
    function sayName () {
        console.log(this.name)
    }
    var o = {}
    o.name = 'jack'
    o.sayName = sayName
    o.sayName() // jack
    //               ,this        
    1.      
    function Test () {
        this.x = 1
    }
    var o = new Test()
    o.x //1
    
    
    2.    this      ,     
    var x = 0
    function Test () {
        this.x = 1
    }
    var o = new Test()
    o.x // 1
    
    
    3.        
    function Person(name){
        this.name = name
    }
    person.prototype.sayName = function () {
        console.log(this.name)
    }
    var xiaoming  = new Person('xiaoming')
    xioaming.sayName() // xiaoming
    
  • apply 나 call 을 사용 하여 apply 나 call 을 연결 하 는 것 은 함 수 를 호출 하 는 방법 입 니 다. 그들의 첫 번 째 매개 변 수 는 모두 같 습 니 다. 현재 함수 의 호출 대상
  • 을 지정 하 는 데 사 용 됩 니 다.
    var name = 'rose'
    function sayName () {
        console.log(this.name)
    }
    var o = {}
    o.name = 'jack'
    o.sayName = sayName
    o.sayName.apply() //  rose              ,        
    o.sayName.apply(o) //   jack      this    o
    

    이 분석 이 어렵다.
    //    this    
    var name = "Bob";  
    var nameObj ={  
        name : "Tom",  
        showName : function(){  
            alert(this.name);  
        },  
        waitShowName : function(){  
            setTimeout(this.showName, 1000);  
        }  
    };  
    
    nameObj.waitShowName();  // Bob
    

    이상 의 문 제 를 해결 하기 위해 서, 우 리 는 먼저 아래 this 의 방향 을 한 걸음 한 걸음 볼 수 있다.
    var person = {
        name: 'jack',
        sayName: function () {
            console.log(this.name)
        }
    }
    var anotherPerson = {
        name: 'rose',
        sayName: person.sayName
    }
    anotherPerson.sayName() // rose
    // this      person.sayName    ,         anotherPerson.sayName,  this  anotherPerson,  rose
    
    var name = 'jack'
    var o = {
        name: 'rose',
        sayName: function () {
            console.log(this.name)
        }
    }
    var sayName = o.sayName
    sayName() // jack
    //        ,sayName()           ,  this  window,window.name === 'jack'
    
    var name = 'willie'
    var Jack = {
        name: 'jack',
        sayName: function () {
            console.log(this.name)
        }
    }
    var Rose = {
        name: 'rose',
        sayName: function () {
            var fun = Jack.sayName
            fun()
        }
    }
    Rose.sayName() // willie
    //            ,              ,   this      Rose,         window
    

    브 라 우 저 에서 setTimeout, setInterval, 익명 함수 가 실 행 될 때의 현재 대상 은 전역 대상 window 입 니 다.
    var name = 'wille'
    var o = {
        name: 'jack',
        sayName: function () {
            setTimeout(function () {console.log(this.name)}, 100)
        }
    }
    o.sayName() // wille
    
    //   ES6           ,         
    var name = 'wille'
    var o = {
        name: 'jack',
        sayName: function () {
            setTimeout(() => {console.log(this.na)},100)
        }
    }
    o.sayName() //jack 
    //    setTimeout,setInterval,     ,          ,this         ,       。
    

    사고 문제, 아래 의 this 가 무엇 을 가리 키 는 지, 그리고 원인 을 생각 하 라.
    1:
    var obj = {
        say: function () {
            setTimeout(() => {
              console.log(this)
            }, 0)
        }
    }
    obj.say() //obj
    
    2:
    function test() {
        console.log(this)
    }
    test() // window(  )
    
    3:
    var obj = {
        say: function () {
            function _say () {
                console.log(this)
            }
            return _say.bind(obj)
        }() //      ,  obj       , this     window
    }
    obj.say() // window(  )
    
    4:
    var obj = {}
    obj.say = function () {
        function _say () {
            console.log(this)
        }
        return _say.bind(obj)
    }() //       ,  obj       ,   this  obj
    obj.say() // obj 
    5: 
    var obj = {
        sayName: function () {
            console.log('outer', this)
            return function () {
                console.log('inner', this)
            }
        }() 
    }
    //        ,this  window,            
    //             ,  this      window
    obj.sayName() //outer -> window    inner -> obj
    //        ,   obj.sayName()  this       obj
    //   obj        
    var obj = {
        sayName : function () {
            console.log('inner', this)
        }
    }
    obj.sayName() // obj
    //           ,   obj  sayName ,this        obj
    

    좋은 웹페이지 즐겨찾기