웹/javascript

vue에서의 this

java개발자 2018. 6. 13. 10:39

vue를 공부하면서 다음과 같은 설명글을 보았다. 

왜 this가 vm 자신인가? 라는 의문이 생김.

출처: https://joshua1988.github.io/web-development/vuejs/vuejs-tutorial-for-beginner/


var vm = new Vue({
  data: {
    a: 1
  },
  created: function () {
    // this 는 vm 을 가리킴
    console.log('a is: ' + this.a)
  }
})


실제로 구성해보니 정말 그랬더라.


/*
방법1
*/
function A(){
console.log(this);
}
new A(); // this는 A자신
A(); // this는 Window

/*
방법2
*/
function A(args){
args.c();
}
new A({
a: 1,
b: this, // this는 Window
c: function (){
console.log(this); // this는 {a: 1, b: Window, c: ƒ} 왜???????
}
})


this는 실행되는 위치에서 정해지는데, b는 { } 객체 생성시 바로 Window가 정해졌고(아직까진 Window 영역이었음.),

c는 new A 객체 생성시 function 안에서 c function이 호출되면서, 그때 정해지므로 A 자신이 된 것 같다.