user3334963
user3334963

Reputation: 25

Prototype property undefined when used in jquery event handler

I'm having a problem accessing a property of an object from a method on that object. The problem is of the form:

function Person() {
    this.siblings = {
        brothers: ["Adam", "Carl"],
        sisters: ["Betty", "Dorothy"]
    };

    this.first_sister = function() { console.log(this.siblings.sisters[0]); }

    this.button_event = function() { $(".btn").on("click", this.first_sister); }
}

Fanny = new Person();
Fanny.button_event();

Instead of logging "Betty" to the console, my code logs "Uncaught TypeError: Cannot read property 'sisters' of undefined" when the .btn element is pressed.

However, if I open the console and type console.log(Fanny.siblings.sisters[0]), or Fanny.first_sister(), it returns "Betty".

I think it's something to do with how I'm using 'this' in the jquery event handler, but nothing I've tried (that = this, etc) has helped. What's going on?

Upvotes: 1

Views: 586

Answers (1)

user2033671
user2033671

Reputation:

If you have a var that = this at the root of the Person scope that should take care of knowing what this you are referring to.

function Person() {
  var self_person = this;
  self_person.siblings = {
    brothers: ["Adam", "Carl"],
    sisters: ["Betty", "Dorothy"]
  };

  self_person.first_sister = function() {
    $("#out").append(self_person.siblings.sisters[0] + "<br/>");
  }

  self_person.button_event = function() {
    $(".btn").on("click", self_person.first_sister);
  }
}

Fanny = new Person();
Fanny.button_event();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn">Clickme</button>
<br/>
<div id="out"></div>

Upvotes: 1

Related Questions