javascript - Error returning an object attribute in JS -


function objecte(name){      this.name=name;  }  objecte.prototype.look=function(){      return function(){          alert(this.name);      };  } 

i'm trying access object's attribute when call function, alerts undefined.

extintor = new objecte("extintor");  $(document).on('dblclick',"#extintor",extintor.look()); 

this not lexically defined. need capture value in order ensure returned function can use it.

objecte.prototype.look=function(){     var self = this;     return function() {         alert(self.name);     }; } 

you can use $.proxy

objecte.prototype.look=function(){     return $.proxy(function() {         alert(this.name);     }, this); } 

or .bind() in modern browsers

objecte.prototype.look=function(){     return function() {         alert(this.name);     }.bind(this); } 

Comments

Popular posts from this blog

php - cannot display multiple markers in google maps v3 from traceroute result -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -