0

I have a method of an object that is called upon click, and the this unfortunately refers to the window object instead of the object that I want it to be referring to.

I've read a several posts that mention this issue, but I have not found/understood any alternatives for my situation.

Any assistance in which direction to go would be appreciated

JSFIDDLE

var IceCream = function(flavor) {
  this.tub = 100;
  this.flavor = flavor;
};

IceCream.prototype = {
  scoop: function() {
    this.updateInventory();
    alert("scooping");
  },
  updateInventory: function() {
    this.tub--;
    alert(this.tub);
  }
};

var vanilla = new IceCream("vanilla");
vanilla.scoop();

$('button').click(vanilla.scoop);
  • 5
    $('button').click(vanilla.scoop.bind(vanilla)); – Paul Jan 11 '16 at 06:02
  • 1
    i do not understand the usage of the 'bind' in that instance. Is the bind telling to use the namespae of vanilla – Matthew J Mammola Jan 11 '16 at 06:07
  • please check http://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript-prototype-functions also updated fiddle https://jsfiddle.net/ky32o3kg/1/ – Sundar Singh Jan 11 '16 at 06:14

3 Answers3

1
$('button').click(function(){
    vanilla.scoop();
});

Change the last line to this should make it work. The $.fn.click function takes a callback, with event as the first argument, and binds the element as this, not window.

------------Edit------------

To make this a little bit cleaner, you can define a function to return a click function. Define your class like so:

IceCream.prototype = {
  scoop: function() {
    this.updateInventory();
    alert("scooping");
  },
  updateInventory: function() {
    this.tub--;
    alert(this.tub);
  },
  makeClickFn: function(){
    var self = this;
    return function(event){
        self.scoop();
    };
  }
};

And when you need to bind the click function:

$('button').click(vanilla.makeClickFn());

jsfiddle: https://jsfiddle.net/L7e71sLL/

rabbit.aaron
  • 2,369
  • 16
  • 25
0
$('button').click(vanilla.scoop.bind(vanilla));

Bind, creates a function whose this variable is bound to the given object. In this case vanilla

Oxi
  • 2,918
  • 17
  • 28
0

Inside $('button').click() the scope will be of the button. So you need to bind the vanilla scope to the onClick function

AKHIL K
  • 84
  • 1
  • 2
  • 11