180bpm

aframe에서의 this와 데이터 클로저 본문

Develop/WebGL

aframe에서의 this와 데이터 클로저

powdersnow 2021. 5. 3. 16:17

예전에 플래시 하던 느낌 난다...

 

C#의 this는 클래스의 인스턴스를 가르키기때문에 변하지 않지만

js의 this는 일반적인 언어와 다르며 또한 엄격선언에 따라 달라진다고 한다. 일관성이 없는거 아니야?

docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/this

 

this 키워드 - C# 참조

this 키워드(C# 참조)

docs.microsoft.com

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this

 

this - JavaScript | MDN

this JavaScript에서 함수의 this 키워드는 다른 언어와 조금 다르게 동작합니다. 또한 엄격 모드와 비엄격 모드에서도 일부 차이가 있습니다. 대부분의 경우 this의 값은 함수를 호출한 방법에 의해 

developer.mozilla.org


그래서 결론은 this는 되도록 쓰지 말고 타겟을 지정해서 써야 한다.

<script>
    var a = 0;
    AFRAME.registerComponent('testcomp', {
      a: 1,
      init: function () {
        console.log("init");
        var a = 2;
        var a2 = 22
        console.log(a);                                        // 2
        console.log(a2);                                       // 22
        console.log(this);                                     // [object Object]
        console.log(this.a);                                   // 1
        console.log(this.__proto__.a);                         // 1
        console.log(window.a);                                 // 0
        console.log(document.a);                               // undefined
        console.log(window.document.a);                        // undefined

        this.el.addEventListener('click', function (e) {
          console.log("click");
          var a = 3;
          console.log(a);                                      // 3
          console.log(a2);                                     // 22
          console.log(this);                                   // element -> <a-scene...>
          console.log(this.a);                                 // undefined
          console.log(this.__proto__.a);                       // undefined
          console.log(window.a);                               // 0
          console.log(document.a);                             // undefined
          console.log(window.document.a);                      // undefined
          
          console.log(this.components["testcomp"].a)           // 1
          console.log(this.sceneEl.components["testcomp"].a)   // 1
          console.log(e.currentTarget.components["testcomp"].a)// 1
        });
      },
Comments