2

I have a normal object in javascript, contenting functions and values.

This is my example object:

var MyObject = {
    myData: 1,
    a: function() {},
    b: function() {}   
}

Now in the function a there is some logic that fire on it, but it should change even the value of myData property.

But when i try get it from the method b, that value come as an undefined value, instead of the value changed.

I created a JsFiddle with a small example of the behaviour of the my object. I realized that it how Javascript behave, but I didn't understand why.

Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
Fabrizio Fenoglio
  • 5,405
  • 13
  • 37
  • 72

2 Answers2

2

The issue is because this within the click handlers refers to the element which was clicked, not the object the handler functions are members of. You need to cache this:

a: function () {
    var self = this;
    $('.setValue').click(function() {
        self.myData = 2;
    });
},
b: function () {
    var self = this;
    $('.getValue').click(function() {
        alert(self.myData);
    });
}

Updated fiddle

Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
0

In JavaScript, each function has its own this argument. In your case, you want to access the outer function's this variable so you should do something like this:

var that = this;

Here is the updated jsfiddle: http://jsfiddle.net/xaaLQ/5/

advncd
  • 3,429
  • 1
  • 24
  • 27