views:

47

answers:

2

Code:

function Customer(name){
   this._name=name;
};

Customer.prototype.init=function(){
   $('#SetCreditLevel').click(function(){
      //best way to access this._name ?
      //this now points to DOM element

   });
}
+1  A: 

http://stackoverflow.com/questions/696241/class-method-cant-access-properties could help I think

Senthil
Sorry, this answser deals with pure JavaScript, I'm using jQuery so context is quite different.
Valentin Vasiliev
+1  A: 

Something like this? You could override the value of this by setting your own context, but it is very useful to be able to access the DOM object as this in jQuery, and a fundamental part of how jQuery works. If you were to change that, I'd say you're not hardly using jQuery at all. So instead, i'm passing context as a parameter here...

function Customer(name){
   this._name=name;
};

Customer.prototype.init=function(){
   $('#SetCreditLevel').click((function(context){
       return function() {
           alert(context._name);
           alert(this);
       }
   })(this));
}
David Hedlund
it works, but I don't fully understand how. I see a self executing anonymous function which is passed the context, - this part I understand. The body of this function is a mystery to me, though. Why is function being returned? How does it work?
Valentin Vasiliev
it's the beauty of javascript *scopes*. jQuery's `click` expects a function. so you execute some code that returns a function, which is then used as the `click` input param. the code that's being executed accepts a `context` parameter, and since it does, that becomes part of the *scope* of the inner function, so that it can be accessed there, with whatever value was originally passed to the parent function.
David Hedlund
That's very elegant, real life usage of closures
Valentin Vasiliev