0

I am trying to practice writing object oriented code with javascript, but it's still confusing to me. I've seen some other people ask this question, but I haven't found a real clear answer. I have a property that has a nested function and I want to use one of the properties from the parent class.

var myClass = {
 btn: document.getElementById('btn'),
 color: "#000",

 clickListener: function(){
  this.btn.addEventListener("click", function(){
   this.style.background = myClass.color;
  });
 },
}

This is the only way I can make it work, but it seems weird using the class name inside of the class. Is there a better way to do this or is this normal?

Alex
  • 240
  • 2
  • 6
  • See [this question](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work), shortly put you will want to keep a reference of `this` for your event listener scope. – Etheryte Dec 24 '16 at 18:54

1 Answers1

1

Any function attached to an object is called a "method," and you can access the object it's attached to by referencing "this" in the method scope. Since you're inside a child function scope, store the parent scope and use it:

var myClass = {
    btn: document.getElementById('btn'),
    color: "#000",

    clickListener: function(){
        var self = this;
        this.btn.addEventListener("click", function(){
                this.style.background = self.color;
        });
    },
}

A comment: This isn't usually referred to as a "class" in Javascript speak since it's an object. "classes" are usually functions, that you make instances of using new. Using an object like this is more often referred to as a "singleton."

Andy Ray
  • 26,451
  • 11
  • 86
  • 123