[Javascript] this

2021. 5. 22. 21:00카테고리 없음

728x90

function sum(a,b){
    console.log(this)
    return a+b;
}
function Vue(el) {
    console.log(this);
    this.el = el;
}

new Vue("#app");
//Vue {}
//Vue {el: "#app"}

Vue("#app");
//Window {0: global, 1: global, 2: global, 3: global, 4: global, 5: global, 6: Window, 7: Window, window: Window, self: Window, document: document, name: "", location: Location, …}


 

->함수 객체 생성하여 호출시 this는 객체 자신

new Vue("#app");
//Vue {}
//Vue {el: "#app"}

 

->그냥 함수 호출시 this는 전역Window를 가리킴
Vue("#app");
//Window {0: global, 1: global, 2: global, 3: global, 4: global, 5: global, 6: Window, 7: Window, window: Window, self: Window, document: document, name: "", location: Location, …}

 

 

->비동기 처리시 this

  var vm = this;
        console.log('호출전: ', this);
        fetchNewsList()
             .then(function(response){
                 console.log('호출 후:' , this);
                 //바로 this를 사용하면 this가 Vue객체를 가리키지 않기 때문에 콜백시에는 따로 지정해야함.. 
                 vm.users = response.data
             })
             .catch(function(error){
                 console.log(error);
  var vm = this;
        console.log('호출전: ', this);
        fetchNewsList()
             .then(function(response){
                 console.log('호출 후:' , this);
                 //바로 this를 사용하면 this가 Vue객체를 가리키지 않기 때문에 콜백시에는 따로 지정해야함.. 
                 vm.users = response.data
             })
             .catch(function(error){
                 console.log(error);
             })

}

 

호출전:  VueComponent {_uid: 6, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
NewsView.vue?7def:21 

 

호출 후: undefined

728x90