2

I have this jQuery function

$("#edit-modal").animate({ width: "90%" }, 400, function () {
    this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
    console.log(this.modalWidth);
});

however in the function() is seems like this. isn't known or available, meaning console.log(this.modalWidth); results in undefined.

How can I use my this.property in my complete function?

eko
  • 39,722
  • 10
  • 72
  • 98
Nicolas
  • 4,526
  • 17
  • 50
  • 87

1 Answers1

3

When you pass in an anonymous function, it gets its own this variable.

The quickest way to get around this would be to create a closure reference to this in the outer scope, and use the reference variable inside your callback.

var self = this;
$("#edit-modal").animate({ width: "90%" }, 400, function () {
    self.registrationsPanelWidth = $("#edit-modal").width() - self.modalWidth - 20;
    console.log(self.modalWidth);
});

This is a perfect use case for ES6 arrow functions, by the way. From the documentation on MDN:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

If you're able to use arrow functions in your project, it would look like this:

$("#edit-modal").animate({ width: "90%" }, 400, () => {
    this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
    console.log(this.modalWidth);
});

See the documentation on MDN for more information on arrow functions.

Kevin Kipp
  • 417
  • 6
  • 14