title: How to access 'this' from within an addEventListener?
body: <p>I'm wanting to access <code>this</code> from within an <code>addEventListener</code>.</p>
  <p>With my example below I want to output <code>this.settings.car</code> when a div is clicked.</p>
  <p>I could write <code>var that = this</code> within the <code>this.init = function() { //here }</code> and access it using <code>that.settings.car</code>, however if I run multiple instances of this code then <code>that</code> will always reference the last instance.</p>
  <p>Else I could rewrite the addEventListener to be:</p>
  <pre><code>this.settings.wrap.addEventListener('click', function (e) =&gt; {
       console.log(this.settings.car)
  })
  </code></pre>
  <p>and that'll work, however this will lead to me writing lots of duplicate code instead of 1 function.</p>
  <p>I've been scratching my head at this for a while now. How can I access this from within the <code>this.test</code> function?</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var gauge = (function() {
    return function() {
      
      this.settings = {
        car: undefined,
      }
      
      this.init = function(e) {
        this.settings.wrap = document.querySelector(e.wrapper)
        this.settings.car = this.settings.wrap.innerText     
        
        this.settings.wrap.addEventListener('click', this.test)      
      }   
      
      this.test = function(e) {
  
        console.log('clicked')
        console.log(this.settings.car)
        
      }
      
    }
  }())
  
  
  // init
  let boy = new gauge()
  boy.init({
    wrapper: '.boy'
  })
  
  let girl = new gauge()
  girl.init({
    wrapper: '.girl'
  })</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>div {display:block;background:grey;margin:20px;height:200px;width:200px;color:white;text-align:center;line-height:200px;}</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="boy"&gt;ford&lt;/div&gt;
  &lt;div class="girl"&gt;ferrari&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  <p>Here's a jsbin of the issue: <a href="https://jsbin.com/xayuheyime/1/edit?html,js,console,output" rel="nofollow noreferrer">https://jsbin.com/xayuheyime/1/edit?html,js,console,output</a></p>