6

I can't figure out how to use a Javascript constructor method in a jQuery .click method. I'm trying to get a button's function to change dynamically based on a constructor. Here's the set up:

<button onclick="">
</button>

needs to call a method that changes depending on another button. The following is my broken code:

    function GloveMode (name , array) {

        this.colorArray = array;

        this.displaySettings = function(){

            //Title
            $("#displayTitle").text(this.name);
            //Display Color Set
            $("#displayColors").empty();


            //Totally Broken
            $("#upArrow").click( function(){

                addColor();

            }); 

        };

        this.addColor = function(){

            console.log(this.colorArray.length);

        };
    };

I can't figure out how to get $("#upArrow").click() to call this.colorArray properly, or how to call this.addColor() in the .click() method! Please help.

2
  • 1
    var self = this; self.addColor() { ... } Commented Nov 20, 2015 at 16:08
  • This is where the prototyping aspect of JavaScript comes into play. In theory, you'll want GloveMode to be an entity that contains properties and methods for accessing those properties (if applicable). It should not contain global click handlers though. For instance if you want the click handler to have access to your name property then you'd use GloveMode.name to access the property and return it to the click handler. Commented Nov 20, 2015 at 16:09

1 Answer 1

4

Your Problem is that "this" means something different in each function body. So save the wanted "this" to a variable e.g. "self" and use that.

function GloveMode (name , array) 
{
    var self = this;
    this.colorArray = array;
    this.displaySettings = function()
    {
      //Title
      $("#displayTitle").text(this.name);
      //Display Color Set

      $("#displayColors").empty();

      //Totally Broken
      $("#upArrow").click( function()
      {
         self.addColor();
      }); 

    };

    this.addColor = function()
    {
       console.log(self.colorArray.length);
    };
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I don't understand why a variable representing 'this' needs to be used here, does anybody know why?
Because you defined a function represented by the member variable this.addColor without a name (an anonymous function declaration). So you can reference this function only by the member variable this.addColor. If you would have given the function a name like function addClass()... then, you would have been able to access it as you did in your code example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.