Ludo
Ludo

Reputation: 5280

Can't access a specific variable on this scenario

I can't understand why i can't access that.Friends.name here (see the code below):

UPDATE

JS

function AClass(_Friends) {
  var that = this;
  this.Friends = _Friends;

  this.doSomething = function() {
    console.log(that.Friends.name); // Uncaught TypeError: Cannot read property 'name' of undefined 
  };
}

var A = new AClass({ name: 'toto' });
$('button').click(A.doSomething);

HTML

<button>TRY!</button>

I use var that = this on the controller of my classes because i could be interesting about calling my methods on callbacks (like in this example), i am not very proud of this, do you have any better way to make it works (maybe it's a good idea te redefined this here) ?

Upvotes: 1

Views: 41

Answers (2)

Matt
Matt

Reputation: 75307

By passing doSomething directly, you're detaching it from the object. jQuery or no jQuery, this would stop working.

However, to definately make it stop working (if that makes any sense), jQuery forces the value of this to be the element clicked inside a handler anyway.

To fix this (haha), you simple need to use an anonymous function;

$('button').click(function () {
    A.doSomething();
});

Now, the value of the anonymous function gets forced to this, but we really don't care, as it's the value of the doSomething() we're interested in; which, as it's still attached to A, and hasn't been forced via call or apply, it the value we need.

With this, there's no need for var that = this; although its a well used JavaScript idiom/ technique, so I wouldn't worry about it myself.

Upvotes: 1

cdhowie
cdhowie

Reputation: 168988

Friends is a local variable in an outer scope; you can access it directly without using that:

console.log(Friends.name);

Upvotes: 1

Related Questions