如何访问类中作用域之外的变量

时间:2018-01-23 06:25:55

标签: javascript class oop

请参阅以下代码:

class game{

     constructor(){

       this.a = 'Helloword';
       this.add_event();
      }

     add_event(){

        clicked = function(){

           console.log(this.a); // I want to print hellowowrd

             }        


       let i = document.getElementById('aDiv'); //just a div
       i.addEventListener('click',clicked);

      }}

正如您所看到的,在单击的函数中,这指的是div,而不是类,但我想从&#39; this.a&#39;打印HelloWorld,我该怎么做。< / p>

3 个答案:

答案 0 :(得分:1)

您需要将this保留为self

  add_event() {
    var self = this;
    let i = document.getElementById('aDiv'); 
    i.addEventListener('click', function() { //notice that function given as an argument diretly
      console.log(self.a); // I want to print hellowowrd
    } );
  }

<强>演示

&#13;
&#13;
class game {
  constructor() {
    this.a = 'Helloword';
    this.add_event();
  }

  add_event() {
    var self = this;
    let i = document.getElementById('aDiv'); // just a div
    i.addEventListener('click', function() {
      console.log(self.a); // I want to print hellowowrd
    } );
  }
}
console.log( new game() )
&#13;
<div id="aDiv">aDiv</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试使用self = this

class game{

 constructor(){

   this.a = 'Helloword';
   this.add_event();
  }

 add_event(){
    var self = this
    clicked = function(){

       console.log(self.a); // I want to print hellowowrd

         }        


   let i = document.getElementById('aDiv'); //just a div
   i.addEventListener('click',clicked);

  }}

或者我猜你可以使用胖箭头语法

clicked (()=>{
       console.log(this.a);
})

我认为这样可行。

答案 2 :(得分:0)

只需点击箭头功能:

 add_event(){
    const clicked = () =>{
       console.log(this.a); // It prints hellowowrd
    };
}