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
  • 331,213
  • 40
  • 305
  • 339
Fabrizio Fenoglio
  • 5,767
  • 14
  • 38
  • 75
  • It's probably the scope – cr0ss Jun 03 '14 at 18:35
  • `this` reference is not carried over into your event handlers. You need to assign it to another variable outside the handlers and access it through the closure, `var self = this;`. – Keen Jun 03 '14 at 18:35

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
  • 331,213
  • 40
  • 305
  • 339
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,787
  • 1
  • 25
  • 31